def _is_softbank_fp(*args, **kwargs): device = get_current_device() if not device.is_featurephone: # FPじゃない return False return device.is_softbank
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """ device = get_current_device() if device.is_smartphone: template_dirs = settings.SMARTPHONE_TEMPLATE_DIRS else: template_dirs = settings.PC_TEMPLATE_DIRS # if not template_dirs: # if device.is_featurephone: # template_dirs = settings.TEMPLATE_DIRS # else if device.is_smartphone: # template_dirs = settings.SMARTPHONE_TEMPLATE_DIRS for template_dir in template_dirs: try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise except ValueError: # The joined path was located outside of this particular # template_dir (it might be inside another one, so this isn't # fatal). pass
def spam(domain, color=None): device = get_current_device() request = get_current_request() return { 'color' : color or 'red', 'device': device, 'domain': domain, }
def load_template_source(self, template_name, template_dirs=None): tried = [] if not template_dirs: device = get_current_device() if device and device.is_featurephone: template_dirs = settings.TEMPLATE_DIRS else: template_dirs = settings.SMARTPHONE_TEMPLATE_DIRS for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (replace_entity(file.read().decode( settings.FILE_CHARSET)), filepath) finally: file.close() except IOError: tried.append(filepath) if tried: error_msg = "Tried %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg)
def _render(request, animation_name, next_url, params, replace_images=None, replace_clips=None, using_reel=False): """ デバイスにあわせてレンダリングする種類を切り替える """ if get_current_device().is_featurephone: # FP用SWF out_swf = _render_swf(animation_name, params=params, replace_images=replace_images, replace_clips=replace_clips) # ヘッダ付与して返す response = HttpResponse(mimetype="application/x-shockwave-flash") response.write(out_swf) if settings.DEBUG: _raise_if_swf_size_is_too_large(response) return response # SP return _render_html( request, animation_name, next_url, params=params, replace_images=replace_images, replace_clips=replace_clips, using_reel=using_reel, )
def _security_check(request, session_id): """ Security check using cookie cookieによるセキュリティチェック """ #リクエストサービスのコールバックにcookieチェックは不要 if settings.GREE_REQUEST_API and request.path == reverse(settings.GREE_REQUEST_API_HEADER): return True from mobilejp.middleware.mobile import get_current_device device = get_current_device() Log.debug("_security_check device.is_webview %s" % device.is_webview) if device.is_webview: Log.debug("[Method] _security_check webview Pass") return True Log.debug("[Method] _security_check ") ua = request.META.get('HTTP_USER_AGENT', None) if ua is None: return False security_name = request.COOKIES.get(_get_security_name(), u'') m = hashlib.md5() m.update(ua) m.update(str(session_id)) Log.debug("[Method] _security_check security_name: %s", security_name) Log.debug("[Method] _security_check m.hexdigest: %s", m.hexdigest()) return m.hexdigest() == security_name
def get_token(self): """ Return the oauth_token. oauth_tokenを返す """ if self.token: return self.token oauth_token = oauth_token_secret = None if self.request: if get_current_device().is_smartphone: # For smart phone # スマートフォン用 session_data = get_session_data(self.request) oauth_token = session_data["oauth_token"] oauth_token_secret = session_data["oauth_token_secret"] else: # For feature phone # フィーチャーフォン用 auth_string = self.request.META.get("HTTP_AUTHORIZATION", "") if auth_string: for param in auth_string.split(","): keyValuePair = param.strip().split("=", 1) if len(keyValuePair) == 2: value = keyValuePair[1].strip('"').encode("utf-8") if keyValuePair[0] == "oauth_token": oauth_token = value if keyValuePair[0] == "oauth_token_secret": oauth_token_secret = value if oauth_token_secret and oauth_token: self.token = oauth.OAuthToken(oauth_token, oauth_token_secret) return self.token
def _create_endpoint_url(self, path, secure=False, url_tail=None): """ FP/SP/WEBVIEW判定し対応したendpoint_urlを返す """ protocol = "https" if secure else "http" from mobilejp.middleware.mobile import get_current_device device = get_current_device() if device: if device.is_webview: endpoint = self.container["endpoint_webview"] elif device.is_smartphone: endpoint = self.container["endpoint_sp"] else: endpoint = self.container["endpoint_fp"] else: endpoint = self.container["endpoint_fp"] Log.debug("url_tail %s " % url_tail) if url_tail or url_tail == "": url = "%s://%s%s%s" % (protocol, endpoint, url_tail, path) else: url = "%s://%s%s%s" % (protocol, endpoint, self.container["api_url_tail"], path) return url
def clean(self, value): """ Validates max_length and min_length. Returns a Unicode object. """ super(CharField, self).clean(value) if value in EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if self.max_length is not None and value_length > self.max_length: raise ValidationError(self.error_messages['max_length'] % { 'max': self.max_length, 'length': value_length }) if self.min_length is not None and value_length < self.min_length: raise ValidationError(self.error_messages['min_length'] % { 'min': self.min_length, 'length': value_length }) device = get_current_device() value = quote(value, device.short_carrier) return value
def render(self, context): name = self.name.resolve(context) try: device = None if context.has_key('device'): device = context['device'] #カスタムタグから使えるように修正 elif context.has_key('context'): device = context['context']['device'] if not device: device = get_current_device() if device.is_au and name in EZWEB_FALLBACK: return mark_safe(EZWEB_FALLBACK[name]) elif device.is_softbank and name in SOFTBANK_FALLBACK: return mark_safe(SOFTBANK_FALLBACK[name]) elif device.is_smartphone: if device.is_android: return '' else: return mark_safe(mobilejp_emoji.get_emoji_by_name(name, 'S')) # print "render------0" # print name # print "------" # print mark_safe(EMOJI_NAME_TO_UNICODE[name]) # print "render------1" if name in BANNED_EMOJI: raise InvalidEmojiError return mark_safe(EMOJI_NAME_TO_UNICODE[name]) except KeyError: return u'[%s]' % name
def _render(request, animation_name, next_url, params, replace_images=None, replace_clips=None, using_reel=False): """ デバイスにあわせてレンダリングする種類を切り替える """ if get_current_device().is_featurephone: # FP用SWF out_swf = _render_swf(animation_name, params=params, replace_images=replace_images, replace_clips=replace_clips) # ヘッダ付与して返す response = HttpResponse(mimetype='application/x-shockwave-flash') response.write(out_swf) if settings.DEBUG: _raise_if_swf_size_is_too_large(response) return response # SP return _render_html(request, animation_name, next_url, params=params, replace_images=replace_images, replace_clips=replace_clips, using_reel=using_reel)
def _security_check(request, session_id): """ Security check using cookie cookieによるセキュリティチェック """ #リクエストサービスのコールバックにcookieチェックは不要 if settings.GREE_REQUEST_API and request.path == reverse( settings.GREE_REQUEST_API_HEADER): return True from mobilejp.middleware.mobile import get_current_device device = get_current_device() Log.debug("_security_check device.is_webview %s" % device.is_webview) if device.is_webview: Log.debug("[Method] _security_check webview Pass") return True Log.debug("[Method] _security_check ") ua = request.META.get('HTTP_USER_AGENT', None) if ua is None: return False security_name = request.COOKIES.get(_get_security_name(), u'') m = hashlib.md5() m.update(ua) m.update(str(session_id)) Log.debug("[Method] _security_check security_name: %s", security_name) Log.debug("[Method] _security_check m.hexdigest: %s", m.hexdigest()) return m.hexdigest() == security_name
def get_token(self): """ Return the oauth_token. oauth_tokenを返す """ if self.token: return self.token oauth_token = oauth_token_secret = None if self.request: if get_current_device().is_smartphone: #For smart phone # スマートフォン用 session_data = get_session_data(self.request) oauth_token = session_data['oauth_token'] oauth_token_secret = session_data['oauth_token_secret'] else: #For feature phone # フィーチャーフォン用 auth_string = self.request.META.get('HTTP_AUTHORIZATION', '') if auth_string: for param in auth_string.split(','): keyValuePair = param.strip().split('=', 1) if len(keyValuePair) == 2: value = keyValuePair[1].strip('"').encode('utf-8') if keyValuePair[0] == 'oauth_token': oauth_token = value if keyValuePair[0] == 'oauth_token_secret': oauth_token_secret = value if oauth_token_secret and oauth_token: self.token = oauth.OAuthToken(oauth_token, oauth_token_secret) return self.token
def _create_endpoint_url(self, path, secure=False, url_tail=None): """ FP/SP/WEBVIEW判定し対応したendpoint_urlを返す """ protocol = 'https' if secure else 'http' from mobilejp.middleware.mobile import get_current_device device = get_current_device() if device: if device.is_webview: endpoint = self.container['endpoint_webview'] elif device.is_smartphone: endpoint = self.container['endpoint_sp'] else: endpoint = self.container['endpoint_fp'] else: endpoint = self.container['endpoint_fp'] Log.debug("url_tail %s " % url_tail) if url_tail or url_tail == '': url = '%s://%s%s%s' % (protocol, endpoint, url_tail, path) else: url = '%s://%s%s%s' % (protocol, endpoint, self.container['api_url_tail'], path) return url
def spam(domain, color=None): device = get_current_device() request = get_current_request() return { 'color': color or 'red', 'device': device, 'domain': domain, }
def _verify_sign(request, *args, **kw): """ _verify_sign """ from mobilejp.middleware.mobile import get_current_device device = get_current_device() # # デバッグユーザーの(空)認証 # if settings.OPENSOCIAL_DEBUG: # if settings.OPENSOCIAL_DEBUG_USER_ID: # opensocial_owner_id = settings.OPENSOCIAL_DEBUG_USER_ID # else: # opensocial_owner_id = create_hashed_debug_user_id(request) # request.opensocial_userid = opensocial_owner_id # request.session_id = 'test%s' % opensocial_owner_id # return view_func(request, *args, **kw) request.is_smartphone = False request.is_futurephone = False from mobilejp.middleware.mobile import get_current_device device = get_current_device() if device and device.is_nonmobile() and\ not request.path.startswith('/m/appevent/'): # PCユーザーの認証 request.is_smartphone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.SMARTPHONE_TEMPLATE_DIRS out = _verify_sign_pc(request, *args, **kw) return out elif settings.OPENSOCIAL_SMARTPHONE_DEBUG: # ローカルスマフォ対応でのテスト用 request.is_smartphone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.SMARTPHONE_TEMPLATE_DIRS out = _verify_sign_pc(request, *args, **kw) return out else: # 携帯ユーザーの認証 request.is_futurephone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.FUTUREPHONE_TEMPLATE_DIRS out = _verify_sign_mobile(request, *args, **kw) return out
def _verify_sign(request, *args, **kw): """ _verify_sign """ from mobilejp.middleware.mobile import get_current_device device = get_current_device(); # # デバッグユーザーの(空)認証 # if settings.OPENSOCIAL_DEBUG: # if settings.OPENSOCIAL_DEBUG_USER_ID: # opensocial_owner_id = settings.OPENSOCIAL_DEBUG_USER_ID # else: # opensocial_owner_id = create_hashed_debug_user_id(request) # request.opensocial_userid = opensocial_owner_id # request.session_id = 'test%s' % opensocial_owner_id # return view_func(request, *args, **kw) request.is_smartphone = False request.is_futurephone = False from mobilejp.middleware.mobile import get_current_device device = get_current_device(); if device and device.is_nonmobile() and\ not request.path.startswith('/m/appevent/'): # PCユーザーの認証 request.is_smartphone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.SMARTPHONE_TEMPLATE_DIRS out = _verify_sign_pc(request, *args, **kw) return out elif settings.OPENSOCIAL_SMARTPHONE_DEBUG: # ローカルスマフォ対応でのテスト用 request.is_smartphone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.SMARTPHONE_TEMPLATE_DIRS out = _verify_sign_pc(request, *args, **kw) return out else: # 携帯ユーザーの認証 request.is_futurephone = True if settings.OPENSOCIAL_DEBUG or settings.OPENSOCIAL_SANDBOX: settings.TEMPLATE_DIRS = settings.FUTUREPHONE_TEMPLATE_DIRS out = _verify_sign_mobile(request, *args, **kw) return out
def _oauth_rekey(request, webview_flag=False): """ Reconfigure the keys for Oauth oauth周りのキーを再設定 """ Log.debug("[Method] _oauth_rekey") Log.debug("[Method] _oauth_rekey webview_flag:%s" % webview_flag) if request.REQUEST.get('opensocial_viewer_id', None): Log.debug("[Method] _oauth_rekey flush session") request.session.flush() request.session['opensocial_userid'] = request.REQUEST[ 'opensocial_viewer_id'] request.session['oauth_token'] = request.REQUEST['oauth_token'] request.session['oauth_token_secret'] = request.REQUEST[ 'oauth_token_secret'] request.session.set_expiry(60 * 30) if webview_flag: Log.debug("[Method] _oauth_rekey _set_webview_session") _set_webview_session(request) # Send information about WebView application to app_usr_agent # WebViewアプリ情報をapp_user_agentに # app_user_agent = request.REQUEST.get('X-GREE-User-Agent', '') #いらない # request.session['app_user_agent'] = request.device.name # if request.device.is_webview: # request.session['is_webview'] = True request.session_id = request.session.session_key request.session.save() # display "the authorization success screen" # 認証成功画面を表示 ctx = RequestContext( request, { 'scid': request.session_id, 'next_path': request.path, 'is_webview': request.device.is_webview, 'get_dict': request.GET, 'post_dict': request.POST, }) device = get_current_device() if device.is_webview: return None res = render_to_response(settings.SMARTPHONE_AUTH_SUCCESS_TEMPLATE, ctx) res.set_cookie(settings.SESSION_COOKIE_NAME, request.session_id) # check again # 心配なのでもう一つチェック _security_set(request, res) return res
def _oauth_rekey(request, webview_flag=False): """ Reconfigure the keys for Oauth oauth周りのキーを再設定 """ Log.debug("[Method] _oauth_rekey") Log.debug("[Method] _oauth_rekey webview_flag:%s" % webview_flag) if request.REQUEST.get('opensocial_viewer_id', None): Log.debug("[Method] _oauth_rekey flush session") request.session.flush() request.session['opensocial_userid'] = request.REQUEST['opensocial_viewer_id'] request.session['oauth_token'] = request.REQUEST['oauth_token'] request.session['oauth_token_secret'] = request.REQUEST['oauth_token_secret'] request.session.set_expiry(60 * 30) if webview_flag: Log.debug("[Method] _oauth_rekey _set_webview_session") _set_webview_session(request) # Send information about WebView application to app_usr_agent # WebViewアプリ情報をapp_user_agentに # app_user_agent = request.REQUEST.get('X-GREE-User-Agent', '') #いらない # request.session['app_user_agent'] = request.device.name # if request.device.is_webview: # request.session['is_webview'] = True request.session_id = request.session.session_key request.session.save() # display "the authorization success screen" # 認証成功画面を表示 ctx = RequestContext(request, { 'scid': request.session_id, 'next_path': request.path, 'is_webview': request.device.is_webview, 'get_dict': request.GET, 'post_dict': request.POST, }) device = get_current_device() if device.is_webview: return None res = render_to_response(settings.SMARTPHONE_AUTH_SUCCESS_TEMPLATE, ctx) res.set_cookie(settings.SESSION_COOKIE_NAME, request.session_id) # check again # 心配なのでもう一つチェック _security_set(request, res) return res
def render(self, name, value, attrs=None): if value is None: value = "" value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) dev = get_current_device() istyle_key, istyle_value = switch_istyle(dev.short_carrier, self.istyle) if istyle_key: final_attrs[istyle_key] = istyle_value return mark_safe(u"<textarea%s>%s</textarea>" % (flatatt(final_attrs), escape(value)))
def render(self, context): pager = self.pager.resolve(context) url_name = self.url_name.resolve(context) url_args = [url_arg.resolve(context) for url_arg in self.url_args] next_index = pager['current'].next_page_number() \ if pager['current'].has_next() else None prev_index = pager['current'].previous_page_number() \ if pager['current'].has_previous() else None try: replace_index = url_args.index('#PAGE#') except ValueError: replace_index = len(url_args) url_args.append('#PAGE#') pages = [] next_url = None prev_url = None for index in pager['navigator']: url_args[replace_index] = index # URL生成 device = get_current_device() request = get_current_request() reversed_url = reverse(url_name, args=url_args) if request and not device.is_featurephone: url = opensocial_session_url_convert(reversed_url, request) else: url = opensocial_url_convert(reversed_url) pages.append({ 'index': index, 'url': url, }) if next_index == index: next_url = url elif prev_index == index: prev_url = url pager_context = template.Context({ 'pager': pager, 'pages': pages, 'current_index': pager['current'].number, 'next_url': next_url, 'next_index': next_index, 'prev_url': prev_url, 'prev_index': prev_index, }) pager_template = template.loader.get_template(self.template_name) rendered_html = pager_template.render(pager_context) return rendered_html
def get_device_name(is_featurephone=None): """ 静的ファイル用のデバイス区分名 """ if is_featurephone is None: # Noneならアクセスしているデバイスから取得 is_featurephone = get_current_device().is_featurephone if is_featurephone: return DEVICE_NAME_FEATUREPHONE else: return DEVICE_NAME_SMARTPHONE
def _get_device_type_name(self): device = get_current_device() if not device: return 'no_device' deviceattrs = ['is_webview', 'is_featurephone', 'is_smartphone'] for deviceattr in deviceattrs: if getattr(device, deviceattr, False): # もし is_xxx が True だったらそれを返す return deviceattr else: return 'default'
def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) dev = get_current_device() istyle_key, istyle_value = switch_istyle(dev.short_carrier, self.istyle) if istyle_key: final_attrs[istyle_key] = istyle_value return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value)))
def render(self, context): """ Create OpensocialInviteUrl and return it argument: parser return value: opensocial_invite_url Opensocial Invite URLを生成し、返す 引数 context 返り値 opensocial_invite_url """ from django.core.urlresolvers import reverse args = [arg.resolve(context) for arg in self.args] kwargs = dict([(smart_str(k,'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) callback_url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) if not settings.OPENSOCIAL_DEBUG: # mixi if settings.OPENSOCIAL_CONTAINER == 'mixi.jp': opensocial_invite_url = 'invite:friends?callback=' + urllib.quote( 'http://' + settings.SITE_DOMAIN + callback_url) # mobage elif settings.OPENSOCIAL_CONTAINER[-7:] == 'mbga.jp': opensocial_invite_url = 'invite:friends?guid=ON&url=' + urllib.quote( 'http://' + settings.SITE_DOMAIN + callback_url) # gree elif settings.OPENSOCIAL_CONTAINER.endswith(GREE): opensocial_invite_url = 'invite:friends?callbackurl=' + urllib.quote( 'http://' + settings.SITE_DOMAIN + callback_url) if self.body: body = resolve_variable(self.body, context) from mobilejp.middleware.mobile import get_current_request, get_current_device device = get_current_device() if device.is_softbank: # and request.encoding == 'x_utf8_softbank': body = body.encode('utf-8') else: body = body.encode('shift_jis') opensocial_invite_url += '&body=' + urllib.quote_plus(body) else: opensocial_invite_url = callback_url else: opensocial_invite_url = callback_url return opensocial_invite_url
def render(self, name, value, attrs=None): if value is None: value = "" elif hasattr(value, "strftime"): value = datetime_safe.new_date(value) value = value.strftime(self.format) if attrs is None: attrs = {} dev = get_current_device() istyle_key, istyle_value = switch_istyle(dev.short_carrier, "numeric") if istyle_key and istyle_value: attrs[istyle_key] = istyle_value return super(MobileDateInput, self).render(name, value, attrs)
def render(self, name, value, attrs=None): if value is None: value = '' elif hasattr(value, 'strftime'): value = datetime_safe.new_date(value) value = value.strftime(self.format) if attrs is None: attrs = {} dev = get_current_device() istyle_key, istyle_value = switch_istyle(dev.short_carrier, 'numeric') if istyle_key and istyle_value: attrs[istyle_key] = istyle_value return super(MobileDateInput, self).render(name, value, attrs)
def clean(self, value): """ Validates max_length and min_length. Returns a Unicode object. """ super(CharField, self).clean(value) if value in EMPTY_VALUES: return u'' value = smart_unicode(value) value_length = len(value) if self.max_length is not None and value_length > self.max_length: raise ValidationError(self.error_messages['max_length'] % {'max': self.max_length, 'length': value_length}) if self.min_length is not None and value_length < self.min_length: raise ValidationError(self.error_messages['min_length'] % {'min': self.min_length, 'length': value_length}) device = get_current_device() value = quote(value, device.short_carrier) return value
def render(self, name, value, attrs=None): if value is None: value = "" if self.istyle: dev = get_current_device() if dev is None: short_carrier = "D" else: short_carrier = dev.short_carrier istyle_key, istyle_value = switch_istyle(short_carrier, self.istyle) if istyle_key: attrs[istyle_key] = istyle_value final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != "": # Only add the 'value' attribute if a value is non-empty. final_attrs["value"] = force_unicode(value) return mark_safe(u"<input%s />" % flatatt(final_attrs))
def opensocial_url_with_domain(reversed_url): u""" SPの場合、リクエストからセッションIDを取得してURLを出す。 FPの場合は opensocial_url のように動作する。 だだし、引数は reverse された URLを取る。 例:: {% opensocial_url_with_domain <reverseされたURL> %} """ from mobilejp.middleware.mobile import get_current_request, get_current_device request = get_current_request() device = get_current_device() if request and not device.is_featurephone: url = opensocial_session_url_convert(reversed_url, request) else: url = opensocial_url_convert(reversed_url) return url
def device_type(self): """ Device Type: WebView: iOS: 4 WebView: Android: 3 WebApp : Smartphone: 2 WebApp : Featurephone: 1 """ device_obj = get_current_device() if device_obj.is_webview: if device_obj.is_ios: device_type = 4 elif device_obj.is_android: device_type = 3 elif device_obj.is_smartphone: device_type = 2 elif device_obj.is_featurephone: device_type = 1 return device_type
def render(self, name, value, attrs=None): if value is None: value = '' if self.istyle: dev = get_current_device() if dev is None: short_carrier = 'D' else: short_carrier = dev.short_carrier istyle_key, istyle_value = switch_istyle(short_carrier, self.istyle) if istyle_key: attrs[istyle_key] = istyle_value final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def get_device(name=None, mobilejp_device=None): """ mobilejp内のデバイスオブジェクトからImage用のデバイスオブジェクトを返す :param mobilejp_device: :return: """ if name in DEVICE_NAME_MAP: return DEVICE_NAME_MAP[name]() if not mobilejp_device: # 指定が無ければ現在のデバイスを取得 mobilejp_device = get_current_device() # mobilejpのdeviceクラスから検索 if mobilejp_device: for device_class in BaseDevice.__subclasses__(): if device_class.check(mobilejp_device): return device_class(mobilejp_device) # 該当デバイス無し return UnknownDevice(mobilejp_device)
def render(self, name, value, attrs=None, choices=()): """ Override """ if value is None: value = "" final_attrs = self.build_attrs(attrs, name=name) size = final_attrs.pop("fontsize", 1) dev = get_current_device() if size and (dev.is_ezweb() or dev.is_nonmobile()): format = u'<option value="%%s"%%s><font size="%s">%%s</font></option>' % size else: format = u'<option value="%s"%s>%s</option>' output = [u"<select%s>" % flatatt(final_attrs)] str_value = smart_unicode(value) # Normalize to string. for option_value, option_label in chain(self.choices, choices): option_value = smart_unicode(option_value) selected_html = (option_value == str_value) and u' selected="selected"' or "" output.append(format % (escape(option_value), selected_html, escape(smart_unicode(option_label)))) output.append(u"</select>") return mark_safe(u"".join(output))
def render(self, name, value, attrs=None, choices=()): """ Override """ if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) size = final_attrs.pop('fontsize', 1) dev = get_current_device() if size and (dev.is_ezweb() or dev.is_nonmobile()): format = u'<option value="%%s"%%s><font size="%s">%%s</font></option>' % size else: format = u'<option value="%s"%s>%s</option>' output = [u'<select%s>' % flatatt(final_attrs)] str_value = smart_unicode(value) # Normalize to string. for option_value, option_label in chain(self.choices, choices): option_value = smart_unicode(option_value) selected_html = (option_value == str_value) and u' selected="selected"' or '' output.append(format % (escape(option_value), selected_html, escape(smart_unicode(option_label)))) output.append(u'</select>') return mark_safe(u''.join(output))
def load_template_source(self, template_name, template_dirs=None): tried = [] if not template_dirs: device = get_current_device() if device and device.is_featurephone: template_dirs = settings.TEMPLATE_DIRS else: template_dirs = settings.SMARTPHONE_TEMPLATE_DIRS for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (replace_entity(file.read().decode(settings.FILE_CHARSET)), filepath) finally: file.close() except IOError: tried.append(filepath) if tried: error_msg = "Tried %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg)
def render(self, context): name = self.name.resolve(context) try: device = None if context.has_key('device'): device = context['device'] #カスタムタグから使えるように修正 elif context.has_key('context'): device = context['context']['device'] if not device: device = get_current_device() if device.is_au and name in EZWEB_FALLBACK: return mark_safe(EZWEB_FALLBACK[name]) elif device.is_softbank and name in SOFTBANK_FALLBACK: return mark_safe(SOFTBANK_FALLBACK[name]) elif device.is_smartphone: if device.is_android: return '' else: return mark_safe( mobilejp_emoji.get_emoji_by_name(name, 'S')) # print "render------0" # print name # print "------" # print mark_safe(EMOJI_NAME_TO_UNICODE[name]) # print "render------1" if name in BANNED_EMOJI: raise InvalidEmojiError return mark_safe(EMOJI_NAME_TO_UNICODE[name]) except KeyError: return u'[%s]' % name
def oauth_signature(request): """ oauth signature authorization How it will be proceed If debug-mode: "None" will be returned If actual-mode: if SP,or PC user: go to _verify_sign_pc if FP: go to _verify_mobile oauth signature 認証 処理の流れ デバッグモード時: 「None」が返される 本番モード: スマホ,PCユーザーの場合: _verify_sign_pc処理へ フューチャーフォンユーザーの場合: _verify_sign_mobile処理へ """ Log.debug("[Method] oauth_signature") ####################################################### # 1. requestにデバイス情報を生やす ####################################################### is_smartphone = False is_featurephone = False device = get_current_device() if device.is_featurephone: is_featurephone = True else: is_smartphone = True if settings.OPENSOCIAL_DEBUG and settings.OPENSOCIAL_SMARTPHONE_DEBUG: is_smartphone = True is_featurephone = False request.is_smartphone = is_smartphone request.is_featurephone = is_featurephone request.device = device # WebViewアプリ情報をapp_user_agentに設定 # TODO: 複数のプラットフォームに対応する際はapp_user_agentを分岐に変更 # app_user_agent = request.REQUEST.get('X-GREE-User-Agent', '') request.session['app_user_agent'] = device.name Log.debug("is_webview:::::: device.is_webview=%s" % device.is_webview) Log.debug("is_webview:::::: session.is_webview=%s" % request.session.get('is_webview')) if device.is_webview: _set_webview_session(request) # request.session['is_webview'] = True # request.session.save() Log.debug("is_webview:::::: session.is_webview=%s" % request.session.get('is_webview')) ####################################################### # 1. End ####################################################### # Use this after the authorization # 認証後に使おう #request.opensocial_viewer_id = str(request.REQUEST.get('opensocial_viewer_id')) # Authorizaiton of debug User # デバッグユーザーの(空)認証 if settings.OPENSOCIAL_DEBUG: if settings.OPENSOCIAL_DEBUG_USER_ID: opensocial_owner_id = settings.OPENSOCIAL_DEBUG_USER_ID else: opensocial_owner_id = create_hashed_debug_user_id(request) opensocial_userid = str(opensocial_owner_id) request.session['opensocial_userid'] = opensocial_userid request.opensocial_viewer_id = str(opensocial_owner_id) # if is_smartphone: # for the testing smartphone # ローカルスマフォ対応でのテスト用 # return _verify_sign_pc(request) return None if request.is_smartphone and not request.path.startswith('/m/appevent/'): # authorization of PC user # スマホ/PC ユーザーの認証 return _verify_sign_pc(request) else: # authorization of mobile user # 携帯ユーザーの認証 return _verify_sign_mobile(request)
class URLNode(Node): """ URLNode """ def __init__(self, view_name, args, kwargs, asvar, converter, query=None): """ argument view_name: Letters args: list kwargs: dictionary asvar: converter: query:dictionary 引数 view_name : 文字列 args : リスト kwargs : 辞書 asvar : converter : query : 辞書 """ self.view_name = view_name self.args = args self.kwargs = kwargs self.asvar = asvar self.converter = converter self.query = query def render(self, context): """ Create URL and return it. argument: context return value: url or '' URLを生成し、返す 引数 context 返り値 url or '' """ #Log.debug("UrlNode 1") from django.core.urlresolvers import reverse, NoReverseMatch args = [arg.resolve(context) for arg in self.args] kwargs = dict([(smart_str(k,'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) try: #if view_name is included in context,use it. # view_nameがコンテキストに含まれる変数名ならば展開して使う view_name = resolve_variable(self.view_name, context) except template.VariableDoesNotExist: view_name = self.view_name if 'request' in context: request = context['request'] else: request = None url = '' try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app) except NoReverseMatch, e: if getattr(settings, 'ERROR_PAGE_MAIL', False): try: try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" subject = 'opensocial_url_error' message = str(e) + '\r\n\r\n' + request_repr mail_admins(subject, message) except: pass if settings.SETTINGS_MODULE: project_name = settings.SETTINGS_MODULE.split('.')[0] try: url = reverse(project_name + '.' + view_name, args=args, kwargs=kwargs, current_app=context.current_app) except NoReverseMatch: if self.asvar is None: raise e else: if self.asvar is None: raise e from mobilejp.middleware.mobile import get_current_request, get_current_device request= get_current_request() device = get_current_device() if request and not device.is_featurephone: if self.query: url = opensocial_session_url_convert(url, request, resolve_variable(self.query, context)) else: url = opensocial_session_url_convert(url, request) # from mobilejp.middleware.mobile import get_is_webview # if get_is_webview(): # url += '&is_webview=True' else: if self.query: url = self.converter(url, resolve_variable(self.query, context)) else: url = self.converter(url) if self.asvar: context[self.asvar] = url return '' else: return url