Example #1
0
    def get(self, request, *args, **kwargs):
        channel_data = self.get_channel_data(*args, **kwargs)

        hours_within = safe_cast(request.GET.get("hours_within"), int)
        incl_unav = safe_cast(request.GET.get("incl_unav"), bool)
        period_count = safe_cast(request.GET.get("period"), int) or Website.Message.DefaultPeriodCount
        if period_count <= 0:
            messages.warning(request, _("Period count cannot be less than or equal to 0."))
            period_count = Website.Message.DefaultPeriodCount

        # Get starting timestamp
        dt_start = self.get_timestamp(
            request, "start",
            msg_parse_failed=_("Failed to parse the starting timestamp. Received: {}"),
            msg_out_of_range=_("Start time out of range.")
        )

        # Get ending timestamp
        dt_end = self.get_timestamp(
            request, "end",
            msg_parse_failed=_("Failed to parse the ending timestamp. Received: {}"),
            msg_out_of_range=_("End time out of range.")
        )

        # Check starting and ending timestamp
        if dt_start and dt_end and dt_start > dt_end:
            dt_start = None
            dt_end = None
            messages.warning(
                request, _("Invalid timestamp: Ending time is before the starting time."))

        channel_name = channel_data.model.get_channel_name(get_root_oid(request))

        pkg = get_msg_stats_data_package(
            channel_data.model, get_current_timezone(), incl_unav,
            hours_within=hours_within, start=dt_start, end=dt_end, period_count=period_count)

        hours_within = pkg[KEY_MSG_INTV_FLOW].hr_range or hours_within
        msg_count = pkg[KEY_MSG_USER_CHANNEL].msg_count

        ctxt = {
            "channel_name": channel_name,
            "channel_data": channel_data.model,
            "hr_range": hours_within,
            "dt_start": dt_start.replace(tzinfo=None).isoformat() if dt_start else "",
            "dt_end": dt_end.replace(tzinfo=None).isoformat() if dt_end else "",
            "message_frequency": (hours_within * 3600) / msg_count if msg_count > 0 else 0,
            "incl_unav": incl_unav,
            "period_count": period_count
        }
        ctxt.update(pkg)

        return render_template(
            self.request, _("Channel Message Stats - {}").format(channel_name),
            "info/msgstats/main.html", ctxt, nav_param=kwargs)
Example #2
0
    def get(self, request, *args, **kwargs):
        # `kwargs` will be used as `nav_param` so extract channel_oid from `kwargs` instead of creating param.
        channel_oid_str = kwargs.get("channel_oid", "")
        channel_oid = safe_cast(channel_oid_str, ObjectId)
        u_profs = ProfileManager.get_user_profiles(channel_oid, get_root_oid(request))

        if u_profs:
            return render_template(
                self.request, _("Channel Management - {}").format(channel_oid), "account/channel/manage.html", {
                    "user_profiles": u_profs,
                    "perm_sum": sorted(ProfileManager.get_permissions(u_profs), key=lambda x: x.code),
                    "channel_oid": channel_oid
                }, nav_param=kwargs)
        else:
            c_prof = ChannelManager.get_channel_oid(channel_oid)

            if c_prof:
                messages.info(
                    request, _("You are redirected to the channel info page "
                               "because you don't have any connections linked to the channel."),
                    extra_tags="info"
                )

                return redirect(reverse("info.channel", kwargs={"channel_oid": channel_oid}))
            else:
                return WebsiteErrorView.website_error(
                    request, WebsiteError.PROFILE_LINK_NOT_FOUND, {"channel_oid": channel_oid_str})
Example #3
0
def get_profile_data(kwargs) -> ProfileDataGetResult:
    profile_oid_str = kwargs.get("profile_oid", "")
    profile_oid = safe_cast(profile_oid_str, ObjectId)

    model = ProfileManager.get_profile(profile_oid)

    return ProfileDataGetResult(ok=model is not None, model=model, oid_org=profile_oid_str)
Example #4
0
def get_channel_data(kwargs) -> ChannelDataGetResult:
    channel_oid_str = kwargs.get("channel_oid", "")
    channel_oid = safe_cast(channel_oid_str, ObjectId)

    model = ChannelManager.get_channel_oid(channel_oid)

    return ChannelDataGetResult(ok=model is not None, model=model, oid_org=channel_oid_str)
Example #5
0
    def get(self, request, *args, **kwargs):
        keyword = request.GET.get("w")
        include_inactive = safe_cast(request.GET.get("include_inactive"), bool)

        channel_data = self.get_channel_data(*args, **kwargs)
        channel_name = channel_data.model.get_channel_name(
            get_root_oid(request))

        module_list = list(
            AutoReplyManager.get_conn_list(channel_data.model.id, keyword,
                                           not include_inactive))

        uids = []
        for module in module_list:
            uids.append(module.creator_oid)
            if not module.active and module.remover_oid:
                uids.append(module.remover_oid)

        username_dict = IdentitySearcher.get_batch_user_name(
            uids, channel_data.model, on_not_found="")

        return render_template(
            request,
            _("Auto-Reply search in {}").format(channel_name),
            "ar/search-main.html", {
                "channel_name": channel_name,
                "channel_oid": channel_data.model.id,
                "module_list": module_list,
                "username_dict": username_dict,
                "include_inactive": include_inactive,
                "keyword": keyword or ""
            },
            nav_param=kwargs)
Example #6
0
    def get(self, request, *args, **kwargs):
        # `kwargs` will be used as `nav_param` so extract chcoll_oid from `kwargs` instead of creating param.

        # `chcoll_oid` may be misformatted.
        # If so, `safe_cast` will yield `None` while the original parameter needs to be kept for the case of not found.
        chcoll_oid_str = kwargs.get("chcoll_oid", "")
        chcoll_oid = safe_cast(chcoll_oid_str, ObjectId)

        chcoll_data: Optional[
            ChannelCollectionModel] = ChannelCollectionManager.get_chcoll_oid(
                chcoll_oid)

        if not chcoll_data:
            return WebsiteErrorView.website_error(
                request,
                WebsiteError.CHANNEL_COLLECTION_NOT_FOUND,
                {"chcoll_oid": chcoll_oid_str},
                nav_param=kwargs)

        msgdata_1d = MessageStatsDataProcessor.get_user_chcoll_messages(
            chcoll_data, hours_within=24)
        msgdata_7d = MessageStatsDataProcessor.get_user_chcoll_messages(
            chcoll_data, hours_within=168)

        return render_template(
            self.request,
            _("Channel Collection Info - {}").format(chcoll_oid),
            "info/chcoll/main.html", {
                "chcoll_data":
                chcoll_data,
                "chcoll_cch_data":
                InfoProcessor.collate_child_channel_data(
                    get_root_oid(request), chcoll_data.child_channel_oids),
                "user_message_data1d":
                msgdata_1d,
                "user_message_data7d":
                msgdata_7d
            },
            nav_param=kwargs)
Example #7
0
    def post(self, request, **kwargs):
        sender_oid = get_root_oid(request)

        profile_result = get_profile_data(kwargs)

        if not profile_result.ok:
            return HttpResponse(status=404)

        channel_model = ChannelManager.get_channel_oid(
            profile_result.model.channel_oid)

        # --- Get form data

        action = InfoPageActionControl.parse(request.POST.get("action"))
        target_uid = safe_cast(request.POST.get("uid"), ObjectId)

        if not action.is_argument_valid(target_uid):
            return HttpResponse(status=400)

        # --- Check permission

        permissions = ProfileManager.get_user_permissions(
            channel_model.id, sender_oid)

        # --- Execute corresponding action

        profile_oid = profile_result.model.id

        if action == InfoPageActionControl.DETACH:
            return InfoPageActionControl.action_detach(request,
                                                       channel_model.id,
                                                       sender_oid, target_uid,
                                                       permissions,
                                                       profile_oid)
        elif action == InfoPageActionControl.DELETE:
            return InfoPageActionControl.action_delete(request, channel_model,
                                                       profile_oid)
        else:
            return HttpResponse(status=501)
Example #8
0
    def __init__(self, txt: str):
        self.elements = list(set(txt.split(Bot.RandomChoiceSplitter)))
        self.weights = None
        self.elem_ignored = False

        if len(self.elements) > 1 and all(
            [Bot.RandomChoiceWeightSplitter in elem
             for elem in self.elements]):
            temp = []
            self.weights = []

            for elem in self.elements:
                option, weight = elem.split(Bot.RandomChoiceWeightSplitter, 1)

                weight = safe_cast(weight, float)

                if weight:
                    self.weights.append(weight)
                    temp.append(option)
                else:
                    self.elem_ignored = True

            self.elements = temp
Example #9
0
    def get(self, request, *args, **kwargs):
        channel_data = self.get_channel_data(*args, **kwargs)
        hours_within = safe_cast(request.GET.get("hours_within"), int)

        # channel_members = ProfileManager.get_channel_members(channel_oid)  # Reserved for per member analysis

        channel_name = channel_data.model.get_channel_name(
            get_root_oid(request))

        pkg = get_bot_stats_data_package(channel_data.model, hours_within,
                                         get_current_timezone())

        ctxt = {
            "channel_name": channel_name,
            "channel_data": channel_data.model,
            "hr_range": hours_within or pkg[KEY_HR_FLOW].hr_range
        }
        ctxt.update(pkg)

        return render_template(self.request,
                               _("Bot Usage Stats - {}").format(channel_name),
                               "info/botstats/main.html",
                               ctxt,
                               nav_param=kwargs)
Example #10
0
 def _handle_profile_oid_(self):
     self._profile_oid = safe_cast(self._profile_oid, ObjectId)
     if not self._profile_oid:
         self._err[param.Manage.Profile.PROFILE_OID] = self._profile_oid
Example #11
0
 def is_content_sticker(content: Any, online_check) -> bool:
     if online_check:
         return LineStickerManager.is_sticker_exists(content)
     else:
         return safe_cast(content, int) is not None
Example #12
0
def get_limit(param_dict, max_: Optional[int] = None):
    limit = safe_cast(param_dict.get("limit"), int)
    if limit and max_:
        return min(limit, max_)
    else:
        return max_
Example #13
0
 def _handle_channel_oid_(self):
     self._channel_oid = safe_cast(self._channel_oid, ObjectId)