Beispiel #1
0
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get current user
        user_id = self.get_request_param(fh.user_id_parm)
        if user_id in ['', None]:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.user_id_parm))
            return

        user = StreamUser.get_by_id(user_id)
        if user is None:
            fh.bad_request_error(self, response, 'Invalid user')
            return

        # query for all streams owned by user
        my_streams = Stream.get_ids_by_owner(user)

        # query for all streams subscribed to by user
        sub_streams = StreamSubscriber.get_by_user(user)

        # write some stream info
        response['owned_streams'] = [s for s in my_streams]
        response['subscribed_streams'] = [s.stream.id() for s in sub_streams]
        self.write_response(json.dumps(response))
Beispiel #2
0
    def get(self):

        user = StreamUser.get_current_user(self)

        if user:
            login_url = fh.get_logout_url(self, '/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': user.nickName,
            'email': user.email,
            'login_url': login_url,
            'login_text': login_text,
            'stream_name_parm': fh.stream_name_parm,
            'tags_parm': fh.tags_parm,
            'cover_url_parm': fh.cover_url_parm,
            'subs_parm': fh.subscribers_parm
            }

        self.set_content_text_html()
        path = os.path.join(os.path.dirname(__file__), '../../templates/Create.html')
        self.response.write(fh.render_html_template(path, template_values))
Beispiel #3
0
    def post(self):

        user = StreamUser.get_current_user(self)

        if user:
            login_url = fh.get_logout_url(self, '/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        stream_ids = json.loads(self.get_request_param(fh.stream_id_parm))
        stream_names = json.loads(self.get_request_param(fh.stream_name_parm))

        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': user.nickName,
            'login_url': login_url,
            'login_text': login_text,
            'unsub_streams': zip(stream_ids, stream_names),
            'stream_id_parm': fh.stream_id_parm
        }

        self.set_content_text_html()
        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/Unsubscribe.html')
        self.response.write(fh.render_html_template(path, template_values))
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get auth token, if present
        auth_token = urllib.quote(
            str(self.get_request_param(fh.auth_token_parm)))
        user_data_str = urllib2.urlopen(
            'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' +
            auth_token).read()
        user_data = json.loads(user_data_str)

        # get user from auth token
        user = StreamUser.get_by_email(user_data['email'])

        if user is None:
            fh.bad_request_error(self, response, 'Invalid user')
            return

        # query for all streams subscribed to by user
        sub_streams = StreamSubscriber.get_by_user(user)

        # write some stream info
        response = [
            s.stream.get().get_meta_dict_with_most_recent_image_url()
            for s in sub_streams
        ]

        self.write_response(json.dumps(response))
Beispiel #5
0
    def get(self):

        self.set_content_text_plain()
        term = self.get_request_param(fh.autocomplete_parm)

        match_streams = fh.search_stream_index_alpha_return_names(
            term.lower(), 100)
        match_tags = fh.search_tag_index_alpha(term.lower(), 100)

        matches = sorted(match_tags + match_streams, key=search_key)[0:20]
        self.write_response(json.dumps(matches))
Beispiel #6
0
    def get(self):

        self.set_content_text_plain()
        response = {}

        search_string = self.get_request_param(fh.search_string_parm)
        if search_string is None:
            fh.bad_request_error(self, "Search string not found")
            return

        response[fh.tags_parm] = fh.search_tag_index(search_string)
        self.write_response(json.dumps(response))
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get stream name
        stream_id = self.get_request_param(fh.stream_id_parm)
        response[fh.stream_id_parm] = stream_id
        if stream_id is None or stream_id == "":
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        if stream is None:
            fh.bad_request_error(self, response, 'Invalid Stream ID')
            return

        # check that user is the owner of the stream
        user_id = self.get_request_param(fh.user_id_parm)
        if user_id != stream.get_owner_from_db().user_id():
            fh.bad_request_error(self, response, 'Not stream owner')
            return

        # remove stream name entries from the search index
        fh.remove_stream_from_search_index(stream, response)

        # delete the stream
        stream.delete()

        self.write_response(json.dumps(response))
Beispiel #8
0
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get current user
        owner_id = self.get_request_param(fh.user_id_parm)
        owner = StreamUser.get_by_id(owner_id)

        if owner is None:
            fh.bad_request_error(self, response, 'Not logged in')
            return

        # get stream name
        stream_name = self.get_request_param(fh.stream_name_parm)
        response[fh.stream_name_parm] = stream_name
        if stream_name is None or stream_name == "":
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_name_parm))
            return

        # get cover image URL
        cover_url = self.get_request_param(fh.cover_url_parm)
        response[fh.cover_url_parm] = cover_url

        # create new stream
        stream = Stream.create(name=stream_name,
                               owner=owner,
                               cover_url=cover_url)

        if stream is None:
            fh.bad_request_error(
                self, response,
                'Stream {0} already exists for user {1}'.format(
                    stream_name, owner.nickName))
            return

        response[fh.stream_id_parm] = stream.key.id()

        # add stream to document index for searching
        fh.searchablize_stream(stream, response)

        # process subscribers list
        subs = self.get_request_param(fh.subscribers_parm)
        response[fh.subscribers_parm] = subs
        num_added = StreamSubscriber.add_subscribers_by_emails(
            stream, subs.split(';'))
        response['num_new_subscribers'] = num_added

        # process tags list
        #TODO: tags list in create
        tags = self.get_request_param(fh.tags_parm)
        StreamTag.add_tags_to_stream_by_name(stream, tags.split(';'))
        response[fh.tags_parm] = tags

        response['status'] = "Created new stream: {}".format(stream_name)
        self.write_response(json.dumps(response))
Beispiel #9
0
    def get(self):
        index = fh.get_stream_index()

        res = index.get_range(limit=1000)
        prints = "<h2>Stream index name: {}</h2>".format(
            fh.get_stream_index_name())
        prints += "<table>"
        prints += "".join(['{}<br><br>'.format(r.fields) for r in res.results])
        prints += "</table>"

        template_values = {
            'simple_content': prints,
            'showstreamindex_active': True
        }

        self.response.write(template.render(templatepath, template_values))
Beispiel #10
0
    def get(self):
        user = users.get_current_user()

        if user:
            nickname = user.nickname()
            login_url = users.create_logout_url('/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        # get all users
        all_streams = Stream.query().fetch()

        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': user,
            'login_url': login_url,
            'login_text': login_text,
            'app': app_identity.get_application_id(),
            'streams': all_streams
        }

        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/Social.html')
        self.set_content_text_html()
        self.write_response(fh.render_html_template(path, template_values))
Beispiel #11
0
    def get(self):

        error_code = self.get_request_param(fh.error_code_parm)
        error_string = self.get_request_param(fh.message_parm)

        # no error error_code in URL
        if error_code in [None, '']:
            error_code = -1

        if error_string in [None, '']:
            error_string = "An error has occurred!"

        else:
            # get error error_code from URL and convert unicode to integer
            error_code = int(error_code)

            # if error error_code in dictionary, look it up.
            if error_code in fh.error_codes:
                error_string = fh.error_codes[error_code]

        template_values = {
            'error_code': error_code,
            'error_string': error_string
        }

        path = os.path.join(os.path.dirname(__file__), '../../templates/ErrorView.html')
        self.set_content_text_html()
        self.write_response(fh.render_html_template(path, template_values))
    def get(self):

        user = StreamUser.get_current_user(self)

        if user:
            login_url = fh.get_logout_url(self, '/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': user.nickName,
            'login_url': login_url,
            'login_text': login_text,
            'stream_name_parm': fh.stream_name_parm,
            'tags_parm': fh.tags_parm,
            'cover_url_parm': fh.cover_url_parm,
            'subs_parm': fh.subscribers_parm
        }

        search_string = self.get_request_param(fh.search_string_parm)
        if search_string is not None:
            template_values['search_string'] = search_string

        tags = self.get_request_param(fh.tags_parm)
        if tags not in [None, '']:
            s = urllib.unquote(tags).decode('utf8')
            tags = eval(s)
            template_values['search_tags'] = [{
                'name': tag,
                'url': fh.get_viewtag_url(tag)
            } for tag in tags]

        stream_ids = self.get_request_param(fh.stream_id_parm)
        if stream_ids not in [None, '']:
            s = urllib.unquote(stream_ids).decode('utf8')
            ids = eval(s)
            template_values['search_streams'] = Stream.get_batch_by_ids(ids)

        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/StreamSearch.html')
        self.set_content_text_html()
        self.write_response(fh.render_html_template(path, template_values))
Beispiel #13
0
    def get(self):
        index = fh.get_tag_index()

        res = index.get_range(limit=1000)
        prints = "<h2>Tag index name: {}</h2>".format(fh.get_tag_index_name())
        prints += "<table>"
        prints += "".join([
            '<tr><td>{0}</td><td>--</td><td>{1}</td></tr>'.format(
                r.fields[1].value, r.fields[2].value) for r in res.results
        ])
        prints += "</table>"

        template_values = {
            'simple_content': prints,
            'showtagindex_active': True
        }

        self.response.write(template.render(templatepath, template_values))
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get stream name
        stream_id = self.get_request_param(fh.stream_id_parm)
        response[fh.stream_id_parm] = stream_id
        if stream_id in [None, '']:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        if stream is None:
            fh.bad_request_error(self, response, 'Invalid Stream ID')
            return

        # get tag name
        tag_name = self.get_request_param(fh.tag_name_parm)
        if tag_name in [None, '']:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.tag_name_parm))
            return

        # check how many streams have this tag
        st = StreamTag.get_batch_by_tag_name(tag_name)
        n_streams = len(st)

        # get the tag
        tag = Tag.get_by_name(tag_name)
        if tag is not None:
            # remove streamtags
            StreamTag.delete_tag_from_stream(stream, tag)

            # block until new tag is found
            time.sleep(0.01)
            while StreamTag.get_by_stream_and_tag(stream, tag) is not None:
                time.sleep(0.01)

            if n_streams == 1:
                fh.remove_tag_from_search_index(tag_name, {})
                tag.delete()

        redirect_url = str(self.get_request_param(fh.redirect_parm))

        if redirect_url in ['', None]:
            self.write_response(json.dumps(response))
        else:
            self.redirect(redirect_url)
Beispiel #15
0
    def get(self):
        user = StreamUser.get_current_user(self)

        if user:
            login_url = fh.get_logout_url(self, '/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        tag_name = self.get_request_param(fh.tag_name_parm)

        # service call
        tag_service_url = fh.get_tagged_streams_url(tag_name)
        result = urllib2.urlopen(tag_service_url)
        stream_dict = json.loads("".join(result.readlines()))

        stream_ids = stream_dict[fh.stream_id_parm]
        stream_names = stream_dict[fh.stream_name_parm]
        cover_urls = stream_dict[fh.cover_url_parm]
        stream_urls = [fh.get_viewstream_default_url(s) for s in stream_ids]

        streams = []
        for i in range(len(stream_ids)):
            streams.append({
                'name': stream_names[i],
                'coverImageURL': cover_urls[i],
                'url': stream_urls[i]
            })

        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': user.nickName,
            'email': user.email,
            'login_url': login_url,
            'login_text': login_text,
            'tag_name': tag_name,
            'streams': streams
        }

        self.set_content_text_html()
        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/ViewTag.html')
        self.response.write(fh.render_html_template(path, template_values))
    def post(self):

        button = self.get_request_param('submit')
        stream_id = self.get_request_param(fh.stream_id_parm)
        tag_name = self.get_request_param(fh.tag_name_parm)

        if button == 'Add Tag':
            tag_service_url = fh.get_addtag_service_url(stream_id, tag_name)
        elif button == 'Remove Tag':
            tag_service_url = fh.get_removetag_service_url(stream_id, tag_name)

        urllib2.urlopen(tag_service_url)

        redirect_url = str(self.get_request_param(fh.redirect_parm))

        if redirect_url in ['', None]:
            self.redirect('/')
        else:
            self.redirect(redirect_url)
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get stream name
        stream_id = self.get_request_param(fh.stream_id_parm)
        response[fh.stream_id_parm] = stream_id
        if stream_id is None:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        # get current user
        user_id = self.get_request_param(fh.user_id_parm)
        if user_id is None or user_id == "":
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.user_id_parm))
            return

        # get the user
        user = StreamUser.get_by_id(user_id)

        # delete subscription
        result = StreamSubscriber.delete(stream, user)
        if result:
            response['status'] = "Subscription deleted"
        else:
            response['status'] = "Subscription not found"

        redirect_url = str(self.get_request_param(fh.redirect_parm))

        if redirect_url in ['', None]:
            self.write_response(json.dumps(response))
        else:
            self.redirect(redirect_url)
Beispiel #18
0
    def get(self):
        user = StreamUser.get_current_user(self)

        if user:
            nickname = user.nickName
            login_url = users.create_logout_url('/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        all_streams = Stream.get_all_streams()
        item_data = []
        for stream in all_streams:
            items = stream.get_all_items()
            for i in range(len(items)):
                item = items[i]
                prev_ind = i - (i % 10) + 1
                stream_url = fh.get_viewstream_url(stream.get_id(), prev_ind, prev_ind+9, i-prev_ind+1)
                if item.getLatLng() is not None:
                    item_data.append({
                                        "lat": item.latitude,
                                        "lng": item.longitude,
                                        "url": item.URL,
                                        "stream_name": stream.name,
                                        "stream_url": stream_url,
                                        "date_added": str(item.dateAdded)
                                    })
        
        template_values = {
            'html_template': 'MasterTemplate.html',
            'user': nickname,
            'login_url': login_url,
            'login_text': login_text,
            'item_data': item_data
        }

        path = os.path.join(os.path.dirname(__file__), '../../templates/GeoMap.html')
        self.set_content_text_html()
        self.write_response(fh.render_html_template(path, template_values))
Beispiel #19
0
    def get(self):
        """Delete all the docs in the given index."""
        tagindex = fh.get_tag_index()
        streamindex = fh.get_stream_index()
        msg = 'Deleted all documents from indexes'
        for index in [tagindex, streamindex]:
            try:
                while True:
                    # until no more documents, get a list of documents,
                    # constraining the returned objects to contain only the doc ids,
                    # extract the doc ids, and delete the docs.
                    document_ids = [
                        document.doc_id
                        for document in index.get_range(ids_only=True)
                    ]
                    if not document_ids:
                        break
                    index.delete(document_ids)
            except search.DeleteError:
                msg = 'Error removing exceptions'

        template_values = {'simple_content': msg, 'cleartagindex_active': True}

        self.response.write(template.render(templatepath, template_values))
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get stream name
        stream_id = self.get_request_param(fh.stream_id_parm)
        response[fh.stream_id_parm] = stream_id
        if stream_id is None or stream_id == "":
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get current user
        user_id = self.get_request_param(fh.user_id_parm)
        response[fh.user_id_parm] = user_id
        if user_id is None or user_id == "":
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.user_id_parm))
            return

        # create new subscription
        sub = StreamSubscriber.get_by_stream_id_and_user_id(stream_id, user_id)
        if sub is not None:
            response['status'] = True
        else:
            response['status'] = False

        redirect_url = str(self.get_request_param(fh.redirect_parm))

        if redirect_url in ['', None]:
            self.write_response(json.dumps(response))
        else:
            self.redirect(redirect_url)
Beispiel #21
0
    def post(self):
        # make call to createStream service
        parm_dict = self.get_request_parameter_dictionary()

        create_stream_url = 'http://{0}/services/createstream?{1}={2};{3}'.format(os.environ['HTTP_HOST'],
                                                                                  fh.user_id_parm,
                                                                                  StreamUser.get_current_user(self).user_id(),
                                                                                  urllib.urlencode(parm_dict))

        try:
            result = urllib2.urlopen(create_stream_url)
            response = json.loads("".join(result.readlines()))
            redirect_url = fh.get_viewstream_url(response[fh.stream_id_parm], 1, 10)
            self.redirect(redirect_url)
        except urllib2.HTTPError:
            self.redirect('/error?{0}={1}'.format(fh.message_parm, 'Error creating stream'))
    def get(self):

        self.set_content_text_plain()
        response = {}

        # get stream name
        stream_id = self.get_request_param(fh.stream_id_parm)
        response[fh.stream_id_parm] = stream_id
        if stream_id in ['', None]:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        if stream is None:
            fh.bad_request_error(self, response, 'Invalid Stream ID')
            return

        # get tag name
        tag_name = self.get_request_param(fh.tag_name_parm)
        if tag_name in ['', None]:
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.tag_name_parm))
            return

        # get the tag
        tag = Tag.get_or_create_by_name(tag_name.strip().lower())

        # create new streamtag
        StreamTag.add_tags_to_stream_by_name(stream, [tag.name])

        # block until new tag is found
        time.sleep(0.01)
        while StreamTag.get_by_stream_and_tag(stream, tag) is None:
            time.sleep(0.01)

        redirect_url = str(self.get_request_param(fh.redirect_parm))

        if redirect_url in ['', None]:
            self.write_response(json.dumps(response))
        else:
            self.redirect(redirect_url)
Beispiel #23
0
    def get(self):

        self.set_content_text_plain()
        response = {}

        tag_name = self.get_request_param(FH.tag_name_parm)
        response[FH.tag_name_parm] = tag_name

        if tag_name is None or tag_name == '':
            FH.bad_request_error(self, response, "No tag name found")
            return

        tag = Tag.create(tag_name)
        if not tag:
            FH.bad_request_error(self, response,
                                 "Tag {} already exists".format(tag_name))
            return

        # add tag to document index for searching
        FH.searchablize_tag(tag, response)

        response['status'] = "Created new tag: {}".format(tag_name)
        self.write_response(json.dumps(response))
    def post(self):
        response = {}

        # get current user
        try:
            user = StreamUser.get_current_user(self)
        except urllib2.HTTPError:
            fh.bad_request_error(self, response, 'HTTPERROR... authToken = {}'.format(self.get_request_param(fh.auth_token_parm)))
            return
        if user is None:
            fh.bad_request_error(self, response, 'Not logged in')
            return

        stream_id = self.get_request_param(fh.stream_id_parm)
        if stream_id is None or stream_id == '':
            fh.bad_request_error(self, response, 'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        if stream is None:
            fh.bad_request_error(self, response, 'Invalid Stream ID')
            return

        n_ups = max(1, fh.get_num_uploads(self))
        print('\nThere were {} uploads\n'.format(n_ups))
        for i in range(n_ups):
            upload = fh.get_upload_from_filehandler(self, i)
            url = self.get_request_param(fh.url_parm)

            if upload is not None:
                image_url = fh.get_file_url(upload)
                name = upload.filename
            elif url not in [None, '']:
                try:
                    urllib2.urlopen(url)
                    image_url = url
                    name = upload
                except:
                    image_url = None
            else:
                image_url = None

            if image_url is not None:

                iscover = self.get_request_param('iscover')
                if iscover:
                    stream.set_cover_image_url(image_url)
                else:

                    lat = self.get_request_param('lat')
                    print "Latitude = ", lat
                    lng = self.get_request_param('lng')
                    print "Longitude = ", lng

                    # create StreamItem entity
                    item = StreamItem.create(
                        owner=user,
                        file=upload,
                        URL=image_url,
                        name=name,
                        stream=stream,
                        latitude=lat,
                        longitude=lng)

                    # update stream list of images
                    stream.add_item(item)

        # go back to viewstream page
        redirect = str(self.get_request_param(fh.redirect_parm))
        if redirect:
            self.redirect(redirect)
            return
        else:
            self.set_content_text_plain()
            response = {'status': 'Upload successful',
                        'image_url': image_url
                        }
            self.write_response(json.dumps(response))
            return
    def get(self):
        user = users.get_current_user()

        if user:
            nickname = user.nickname()
            login_url = users.create_logout_url('/')
            login_text = 'Sign out'
        else:
            self.redirect("/")
            return

        # retrieve request parameters
        stream_id = self.get_request_param(fh.stream_id_parm)

        # retrieve the stream from the ID
        try:
            stream = (ndb.Key('Stream', int(stream_id))).get()
        except:
            self.redirect('/')
            return

        if stream is None:
            self.redirect('/')
            return

        active_image = self.get_request_param(fh.active_image_parm)
        try:
            active_image = int(active_image)
        except (TypeError, ValueError):
            active_image = 0

        #Increment view counter
        stream.viewList.append(datetime.now())
        stream.numViews = stream.numViews + 1
        stream.put()

        upload_url = blobstore.create_upload_url('/services/upload')

        # get the current image range
        ind1, ind2, status = fh.get_image_range_param(self)
        if ind1 is None or ind2 is None:
            ind1 = 1
            ind2 = images_per_page

        # make call to viewimage service
        viewstream_service_url = fh.get_viewstream_service_url(
            stream_id, ind1, ind2)

        result = urllib2.urlopen(viewstream_service_url)
        response = json.loads("".join(result.readlines()))
        image_urls = response['urls']
        tags = response[fh.tags_parm]
        tags = [{'name': tag, 'url': fh.get_viewtag_url(tag)} for tag in tags]

        #Values for GeoMap
        streamItemsLoc = response['streamItemsLoc']

        # get total number of images and make links
        num_images = response[fh.num_images_parm]

        # get next 10 images link
        next_page_url = None
        if ind2 < num_images:
            next_page_url = fh.get_viewstream_url(stream_id,
                                                  ind1 + images_per_page,
                                                  ind2 + images_per_page)

        # get previous 10 images link
        prev_page_url = None
        if ind1 > 1:
            prev_page_url = fh.get_viewstream_url(stream_id,
                                                  ind1 - images_per_page,
                                                  ind2 - images_per_page)

        # see if user is subscribed to this stream
        # make call to subscribed service
        subscribed_service_url = fh.get_subscribed_service_url(
            user.user_id(), stream_id)

        result = urllib2.urlopen(subscribed_service_url)
        response = json.loads("".join(result.readlines()))
        is_subscribed = response['status']

        redirect_url = urllib2.quote(
            fh.get_viewstream_url(stream_id, ind1, ind2))
        if is_subscribed:
            sub_url = fh.get_unsubscribe_service_url(user.user_id(), stream_id,
                                                     redirect_url)
        else:
            sub_url = fh.get_subscribe_service_url(user.user_id(), stream_id,
                                                   redirect_url)

        item_data = []
        items = stream.get_all_items()
        for i in range(len(items)):
            item = items[i]
            prev_ind = i - (i % 10) + 1
            stream_url = fh.get_viewstream_url(stream.get_id(), prev_ind,
                                               prev_ind + 9, i - prev_ind + 1)
            if item.getLatLng() is not None:
                item_data.append({
                    "lat": item.latitude,
                    "lng": item.longitude,
                    "url": item.URL,
                    "stream_name": stream.name,
                    "stream_url": stream_url,
                    "date_added": str(item.dateAdded)
                })

        template_values = {
            'html_template': 'MasterTemplate.html',
            'stream': stream,
            'stream_id': stream.stream_id(),
            'upload_url': upload_url,
            'image_urls': image_urls,
            'user': user,
            'login_url': login_url,
            'login_text': login_text,
            'is_subscribed': is_subscribed,
            'sub_url': sub_url,
            'tags': tags,
            'tag_name_parm': fh.tag_name_parm,
            'tag_url': fh.get_tagmod_url_noparm(),
            'redirect_url': self.get_current_url(),
            'stream_id_parm': fh.stream_id_parm,
            'redirect_parm': fh.redirect_parm,
            'url_parm': fh.url_parm,
            'item_data': item_data,
            'active_image': active_image
        }

        if next_page_url:
            template_values['next_page_url'] = next_page_url

        if prev_page_url:
            template_values['prev_page_url'] = prev_page_url

        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/ViewStream.html')
        self.response.write(template.render(path, template_values))
    def get(self):

        self.set_content_text_plain()
        response = {}

        stream_id = self.get_request_param(fh.stream_id_parm)
        if stream_id is None or stream_id == '':
            fh.bad_request_error(
                self, response,
                'No parameter {} found'.format(fh.stream_id_parm))
            return

        # get the stream
        stream = Stream.get_by_id(stream_id)

        if stream is None:
            fh.bad_request_error(self, response, 'Invalid Stream ID')
            return

        # write some stream info
        response[fh.stream_name_parm] = stream.name
        response[fh.owner_parm] = stream.get_owner_from_db().nickName
        response[fh.num_images_parm] = len(stream.items)

        # get the indices
        ind1, ind2, status = fh.get_image_range_param(self)
        if ind1 is None or ind2 is None:
            fh.bad_request_error(self, response, status)
            return

        # query for images
        items, in1, ind2 = stream.get_items(ind1, ind2)
        image_urls = [item.URL for item in items]

        if len(image_urls) == 0:
            response[fh.image_range_parm] = None
        else:
            response[fh.image_range_parm] = "{0}-{1}".format(ind1, ind2)

        # get the tags
        stream_tags = StreamTag.get_batch_by_stream(stream)
        response[fh.tags_parm] = [t.get_tag_name() for t in stream_tags]

        #get lat/lng data for GeoMap
        item_loc = []
        for item in items:
            if item.getLatLng() is not None:
                oneItem = []

                oneItem.append(item.stream.id())
                oneItem.append(item.dateAdded.strftime("%Y-%m-%d %H:%M:%S"))

                if item.URL is None:
                    imageURL = fh.get_file_url(item.blobKey)
                else:
                    imageURL = item.URL

                oneItem.append(imageURL)
                oneItem.append(item.latitude)
                oneItem.append(item.longitude)

                item_loc.append(oneItem)

        response['streamItemsLoc'] = item_loc

        response['urls'] = image_urls
        self.write_response(json.dumps(response))