Create a "conversation" identifier to track requests per browser session
336612
function getConversationId(req, res, options) {
    var cookieName = options.conversationIdCookieName;
    var headerName = options.conversationIdHeader;
    var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName];
    if (!conversationId) {
        conversationId = uuid.v1();
    }
    req.conversationId = conversationId;
    res.cookie(cookieName, conversationId, { path: '/' });
    return conversationId;
}
536301
def _make_context(self, request: 'Request'=None, state: Text=None):
        

        if request:
            self.client.user_context({
                'id': request.user.id,
            })
            self.client.extra_context({
                'message': repr(request.stack),
                'register': make_rw(request.register),
            })
            self.client.tags_context({
                'conversation_id': request.conversation.id,
                'from_state': request.register.get(request.register.STATE),
                'state': state,
                'platform': request.platform,
            })
1289533
def edit_conversation(self, id, conversation_starred=None, conversation_subscribed=None, conversation_workflow_state=None, filter=None, filter_mode=None, scope=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - id
        """ID"""
        path["id"] = id

        # OPTIONAL - conversation[workflow_state]
        """Change the state of this conversation"""
        if conversation_workflow_state is not None:
            self._validate_enum(conversation_workflow_state, ["read", "unread", "archived"])
            data["conversation[workflow_state]"] = conversation_workflow_state

        # OPTIONAL - conversation[subscribed]
        """Toggle the current user's subscription to the conversation (only valid for
        group conversations). If unsubscribed, the user will still have access to
        the latest messages, but the conversation won't be automatically flagged
        as unread, nor will it jump to the top of the inbox."""
        if conversation_subscribed is not None:
            data["conversation[subscribed]"] = conversation_subscribed

        # OPTIONAL - conversation[starred]
        """Toggle the starred state of the current user's view of the conversation."""
        if conversation_starred is not None:
            data["conversation[starred]"] = conversation_starred

        # OPTIONAL - scope
        """Used when generating "visible" in the API response. See the explanation
        under the {api:ConversationsController#index index API action}"""
        if scope is not None:
            self._validate_enum(scope, ["unread", "starred", "archived"])
            data["scope"] = scope

        # OPTIONAL - filter
        """Used when generating "visible" in the API response. See the explanation
        under the {api:ConversationsController#index index API action}"""
        if filter is not None:
            data["filter"] = filter

        # OPTIONAL - filter_mode
        """Used when generating "visible" in the API response. See the explanation
        under the {api:ConversationsController#index index API action}"""
        if filter_mode is not None:
            self._validate_enum(filter_mode, ["and", "or", "default or"])
            data["filter_mode"] = filter_mode

        self.logger.debug("PUT /api/v1/conversations/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("PUT", "/api/v1/conversations/{id}".format(**path), data=data, params=params, no_data=True)
550278
function (user_id, cookie, passphrase, callback) {
		var packed_user_id = String.fromCharCode(0, 0, 0, 0, user_id >> 24 & 0xFF, user_id >> 16 & 0xFF, user_id >> 8 & 0xFF, user_id & 0xFF);
		var client_nonce = "";
		for (var i = 0; i < 16; ++i) {
			client_nonce += String.fromCharCode(Math.random() * 256);
		}
		var seed = packed_user_id + unescape(encodeURIComponent(passphrase));
		var data = packed_user_id + _server_nonce + client_nonce;
		var d = ecp.mpn_pack(util.hash_string_to_words(seed));
		var z = ecp.mpn_pack(util.hash_string_to_words(data));
		var r = ecp.mpn_new(8), s = ecp.mpn_new(8);
		ecp.ecp_sign(r, s, ecp.secp224k1_p, ecp.secp224k1_a, ecp.secp224k1_G, ecp.secp224k1_n, d, z, 8);
		request({
			method: "Authenticate",
			user_id: user_id,
			cookie: cookie,
			nonce: btoa(client_nonce),
			signature: [ btoa(util.words_to_string(ecp.mpn_unpack(r))), btoa(util.words_to_string(ecp.mpn_unpack(s))) ],
		}, callback);
	}
944069
def cli(obj, ids, query, filters, attributes):
    """"""
    client = obj['client']
    if ids:
        total = len(ids)
    else:
        if query:
            query = [('q', query)]
        else:
            query = build_query(filters)
        total, _, _ = client.get_count(query)
        ids = [a.id for a in client.get_alerts(query)]

    with click.progressbar(ids, label='Updating {} alerts'.format(total)) as bar:
        for id in bar:
            client.update_attributes(id, dict(a.split('=') for a in attributes))
468737
function Session (client, params) {
  var self = this
  if (!(self instanceof Session)) return new Session(client, params)
  if (!(client instanceof Snapchat)) throw new Error('invalid client')

  self.client = client

  var storiesResponse = params['stories_response']
  var friendsResponse = params['friends_response']
  var updatesResponse = params['updates_response']
  var identity = params['identity_check_response']
  var features = updatesResponse['feature_settings']
  var discover = params['discover']
  var messagingGate = params['messaging_gateway_info']

  var friendStories = storiesResponse['friend_stories'] || []
  var myStories = storiesResponse['my_stories'] || []
  // var groupStories = storiesResponse['my_group_stories'] || []

  var friends = friendsResponse['friends'] || []
  var addedFriends = friendsResponse['added_friends'] || []
  var conversations = params['conversations_response'] || []

  self.backgroundFetchSecret = params['background_fetch_secret_key']
  self.bestFriendUsernames = friendsResponse['bests'] || []

  self.storiesDelta = !!storiesResponse['friend_stories_delta']
  self.emailVerified = !!identity['is_email_verified']
  self.highAccuracyRequiredForNearby = !!identity['is_high_accuracy_required_for_nearby']
  self.requirePhonePasswordConfirmed = !!identity['require_phone_password_confirmed']
  self.redGearDurationMilliseconds = +identity['red_gear_duration_millis']
  self.suggestedFriendFetchThresholdHours = identity['suggested_friend_fetch_threshold_hours'] | 0

  self.messagingGatewayAuth = messagingGate['gateway_auth_token']
  self.messagingGatewayServer = messagingGate['gateway_server']

  // Discover
  self.discoverSupported = (discover['compatibility'] === 'supported')
  self.discoverSharingEnabled = !!discover['sharing_enabled']
  self.discoverGetChannels = discover['get_channels']
  self.discoverResourceParamName = discover['resource_parameter_name']
  self.discoverResourceParamValue = discover['resource_parameter_value']
  self.discoverVideoCatalog = discover['video_catalog']

  // Friends
  self.friends = friends.filter(function (friend) {
    return friend.name !== updatesResponse['username'] && friend.expiration === 0
  }).map(function (friend) {
    return new User(friend)
  })

  // Added friends
  self.addedFriends = addedFriends.map(function (friend) {
    return new User(friend)
  })

  // Conversations
  self.conversations = conversations.map(function (conversation) {
    return new Conversation(conversation)
  })

  // Story collections
  self.stories = friendStories.map(function (collection) {
    return new StoryCollection(self.client, collection)
  })

  // User stories
  self.userStories = myStories.map(function (story) {
    return new UserStory(story)
  })

  // Group stories?
  self.groupStories = [ ] // TODO

  // Added me but not added back
  self.pendingRequests = [ ] // TODO

  // Cash info
  self.canUseCash = !!updatesResponse['allowed_to_use_cash']
  self.isCashActive = !!updatesResponse['is_cash_active']
  self.cashCustomerIdentifier = updatesResponse['cash_customer_id']
  self.cashClientProperties = updatesResponse['client_properties']
  self.cashProvider = updatesResponse['cash_provider']

  // Basic user info
  self.username = updatesResponse['username']
  self.email = updatesResponse['email']
  self.mobileNumber = updatesResponse['mobile']
  self.recieved = updatesResponse['recieved'] | 0
  self.sent = updatesResponse['sent'] | 0
  self.score = updatesResponse['score'] | 0
  self.recents = updatesResponse['recents'] || []
  self.requests = updatesResponse['requests'] || []

  // Account information
  self.addedFriendsTimestamp = new Date(updatesResponse['added_friends_timestamp'])
  self.authToken = updatesResponse['auth_token']
  self.canSeeMatureContent = !!updatesResponse['can_view_mature_content']
  self.countryCode = updatesResponse['country_code'] || 'US'
  self.lastTimestamp = new Date(updatesResponse['cash_provider'])
  self.devicetoken = updatesResponse['device_token']
  self.canSaveStoryToGallery = !!updatesResponse['enable_save_story_to_gallery']
  self.canVideoTranscodingAndroid = !!updatesResponse['enable_video_transcoding_android']
  self.imageCaption = !!updatesResponse['image_caption']
  self.requireRefreshingProfileMedia = !!updatesResponse['require_refreshing_profile_media']
  self.isTwoFAEnabled = !!updatesResponse['is_two_fa_enabled']
  self.lastAddressBookUpdateDate = new Date(updatesResponse['last_address_book_updated_date'])
  self.lastReplayedSnapDate = new Date(updatesResponse['last_replayed_snap_timestamp'])
  self.logged = !!updatesResponse['logged']
  self.mobileVerificationKey = updatesResponse['mobile_verification_key']
  self.canUploadRawThumbnail = !!updatesResponse['raw_thumbnail_upload_enabled']
  self.seenTooltips = updatesResponse['seen_tooltips']
  self.shouldCallToVerifyNumber = !!updatesResponse['should_call_to_verify_number']
  self.shouldTextToVerifyNumber = !!updatesResponse['should_send_text_to_verify_number']
  self.snapchatPhoneNumber = updatesResponse['snapchat_phone_number']
  self.studySettings = updatesResponse['study_settings']
  self.targeting = updatesResponse['targeting']
  self.userIdentifier = updatesResponse['user_id']
  self.videoFiltersEnabled = !!updatesResponse['video_filters_enabled']
  self.QRPath = updatesResponse['qr_path']

  // Preferences
  self.enableNotificationSounds = !!updatesResponse['notification_sound_setting']
  self.numberOfBestFriends = updatesResponse['number_of_best_friends'] | 0
  self.privacyEveryone = !updatesResponse['snap_p']
  self.isSearchableByPhoneNumber = !!updatesResponse['searchable_by_phone_number']
  // self.storyPrivacy = SKStoryPrivacyFromString(updatesResponse['story_privacy']) // TODO

  // Features
  self.enableFrontFacingFlash = !!features[constants.featureSettings.frontFacingFlash]
  self.enablePowerSaveMode = !!features[constants.featureSettings.powerSaveMode]
  self.enableReplaySnaps = !!features[constants.featureSettings.replaySnaps]
  self.enableSmartFilters = !!features[constants.featureSettings.smartFilters]
  self.enableSpecialText = !!features[constants.featureSettings.specialText]
  self.enableSwipeCashMode = !!features[constants.featureSettings.swipeCashMode]
  self.enableVisualFilters = !!features[constants.featureSettings.visualFilters]
  self.enableTravelMode = !!features[constants.featureSettings.travelMode]
}
479381
def requests_session(self, *args, **kwargs):
        
        import requests
        auth1 = self.generate_auth()
        return requests.Session(*args, auth=auth1, **kwargs)
462662
def new_session_callback(fuzzer, edge, resp):
    '''
    
    '''
    fuzzer.logger.info('session is: %s' % hexlify(resp[1:3]).decode())
    fuzzer.target.session_data['session_id'] = resp[1:3]
207348
function(conversationId, participants, callback) {
      conversationId = utils.toUUID(conversationId);
      if (!conversationId) return callback(new Error(utils.i18n.conversations.id));
      if (!utils.isArray(participants)) return callback(new Error(utils.i18n.conversations.participants));
      utils.debug('Conversation addParticipants: ' + conversationId);

      var operations = participants.map(function(participant) {
        return {
          operation: 'add',
          property: 'participants',
          value: participant
        };
      });

      edit(conversationId, operations, callback);
    }
1209094
def process_request(self, request):
        """"""
        
        if COOKIE_KEY in request.COOKIES and \
            request.COOKIES[COOKIE_KEY] == COOKIE_SPAM:
                # Is a known spammer.
                response = HttpResponse("")
                # We do not reveal why it has been forbbiden:
                response.status_code = 404
                if DJANGOSPAM_LOG:
                    logger.log("SPAM REQUEST", request.method,
                       request.path_info,
                       request.META.get("HTTP_USER_AGENT", "undefined"))
                return response
        if DJANGOSPAM_LOG:
            logger.log("PASS REQUEST", request.method, request.path_info,
                       request.META.get("HTTP_USER_AGENT", "undefined"))
        return None
1180850
function(conversationId, userId, text, callback) {
      send(null, conversationId, utils.messageText('user_id', userId, text), callback);
    }
737432
def include_callback_query_chat_id(fn=pair, types='all'):
    
    @_ensure_seeders_list
    def p(seeders, delegator_factory, *args, **kwargs):
        return fn(seeders + [per_callback_query_chat_id(types=types)],
                  delegator_factory, *args, include_callback_query=True, **kwargs)
    return p
1000124
def post_session():
    

    url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL)

    nonce = ''.join([str(random.randint(0, 9)) for i in range(9)])
    _json = {"nonce": str(nonce)}

    try:
        arequest = requests.post(url_string,
                                 data=json.dumps(_json),
                                 headers=API_HEADERS)
        response_json = arequest.json()
        return response_json
    except requests.exceptions.RequestException:
        return None
205050
def index
      @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru)
      @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru)
    end
505331
function(jid_or_user_id) {
        var self = this,
            stanzaParams = {
                from: self.helpers.getUserCurrentJid(),
                to: this.helpers.jidOrUserId(jid_or_user_id),
                type: this.helpers.typeChat(jid_or_user_id)
            },
            builder = Utils.getEnv().browser ? $msg : XMPP.Stanza;

        var stanza = chatUtils.createStanza(builder, stanzaParams);

        stanza.c('composing', {
            xmlns: chatUtils.MARKERS.STATES
        });

        if(Utils.getEnv().browser){
            self.connection.send(stanza);
        } else {
            self.Client.send(stanza);
        }
    }
495925
def user_requests(self, id, **kwargs):
        ""
        api_path = "/api/v2/users/{id}/requests.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
606959
private void processAsyncSessionStoppedCallback (CommsByteBuffer buffer, Conversation conversation) {
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processAsyncSessionStoppedCallback", new Object[]{buffer, conversation});

     final short connectionObjectId = buffer.getShort();
     final short clientSessionId    = buffer.getShort();

     if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "connectionObjectId="+connectionObjectId);
     if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "clientSessionId="+clientSessionId);

     // Obtain the proxy queue group
     final ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
     final ProxyQueueConversationGroup pqcg = convState.getProxyQueueConversationGroup();
     if (pqcg == null) {
       if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "ProxyQueueConversationGroup=null");
       SIErrorException e = new SIErrorException(nls.getFormattedMessage("NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", new Object[] {}, null));
       FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_01, this);
       SibTr.error(tc, "NULL_PROXY_QUEUE_CONV_GROUP_CWSICO8020", e);
       throw e;
     }

     // Obtain the required proxy queue from the proxy queue group and ensure its of the right class (ie not read ahead)
     final ProxyQueue proxyQueue = pqcg.find(clientSessionId);
     if (proxyQueue instanceof AsynchConsumerProxyQueue) {
       final ConsumerSessionProxy consumerSessionProxy = ((AsynchConsumerProxyQueue)proxyQueue).getConsumerSessionProxy();

       //Drive the ConsumerSessionProxy.stoppableConsumerSessionStopped method on a different thread.
       ClientAsynchEventThreadPool.getInstance().dispatchStoppableConsumerSessionStopped(consumerSessionProxy);
     } else {
       if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "proxyQueue not an instance of AsynchConsumerProxyQueue is an instance of "+ proxyQueue.getClass().getName());
       SIErrorException e = new SIErrorException(nls.getFormattedMessage("WRONG_CLASS_CWSICO8021", new Object[] {proxyQueue.getClass().getName()}, null));
       FFDCFilter.processException(e, CLASS_NAME + ".processAsyncSessionStoppedCallback", CommsConstants.PROXYRECEIVELISTENER_SESSION_STOPPED_02, this);
       SibTr.error(tc, "WRONG_CLASS_CWSICO8021", e);
       throw e;
     }

     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "processAsyncSessionStoppedCallback");
   }