Esempio n. 1
0
 def setUp(self):
     video1 = Video(title='video1')
     video2 = Video(title='video2')
     video3 = Video(title='video3')
     video4 = Video(title='video4')
     video1.save()
     video2.save()
     video3.save()
     video4.save()
     category = Category(title='category')
     category.save()
     category2 = Category(title='category2')
     category2.save()
Esempio n. 2
0
    def _execute_crawler(self, term, max_depth, max_breadth):
        token = os.environ.get('TOKEN_YOUTUBE')
        crawler = Crawler(site='youtube',
                          site_token=token,
                          max_breadth=max_breadth,
                          max_depth=max_depth)
        for video in crawler.run(term.split()):
            if Video.objects.filter(id_source=video.id_source).exists():
                continue

            base_url = 'http://www.youtube.com/watch?v='
            db_video = Video(id_source=video.id_source,
                             source='youtube',
                             user=self.get_user(),
                             title=video.title,
                             description=video.description,
                             filename=base_url + video.id_source)
            db_video.save(force_insert=True)  # Could be problematic on sqlite
            for tag in video.tags:
                db_video.tags.add(self.get_tag(tag))

        # Erase CrawlerBot thread controller
        self.mutex.acquire()
        del (self.threads[threading.currentThread().ident])
        self.mutex.release()
Esempio n. 3
0
def create_new_videos(videos_info):
    videos = []
    for video_info in videos_info:
        video = Video(yt_id=video_info['id'],
                      yt_title=video_info['title'],
                      published_at_yt=video_info['published_at'])
        video.title = clean_video_title(video_info['title'])
        video.description = clean_video_description(video_info['description'])
        video.save()
        videos.append(video)
        request = requests.get(video_info['thumbnail_url'], stream=True)
        if request.status_code == requests.codes.ok:
            tempimg = tempfile.NamedTemporaryFile()
            for block in request.iter_content(1024 * 8):
                if not block:
                    break
                tempimg.write(block)
            video.thumbnail = files.File(tempimg)
            video.save()
            # make thumbnail be "cut" in the right ratio for the video thumbnails
            ratio = 275.0 / 154.0
            t_width = int(
                min(video.thumbnail.width, video.thumbnail.height * ratio))
            t_height = int(
                min(video.thumbnail.width / ratio, video.thumbnail.height))
            #center the cut
            y_origin = video.thumbnail.height / 2 - t_height / 2
            y_end = y_origin + t_height
            t_ratio = '0,' + str(y_origin) + str(t_width) + ',' + str(y_end)
            video.thumbnail_ratio = t_ratio
            video.save()
        if 'tags' in video_info:
            for video_tag in video_info['tags']:
                tag = Tag.objects.create(video=video, name=video_tag)
    return videos
Esempio n. 4
0
def init_cocreate(cocreate, generate_slug):
    if len(cocreate.videos) <= 0:
        return
    
    if not cocreate.output_video:
        slug = generate_slug(SLUG_LENGTH)
        video = Video(title=cocreate.title, slug=slug, description=cocreate.description, uploader=cocreate.owner)
        video.save()
        cocreate.output_video = video
        cocreate.save()
    else:
        # reset video status to encoding
        video_status = cocreate.output_video.get_video_status()
        video_status.set_to_encoding()

    #create outline from the sections
    VideoOutline.objects.filter(video=cocreate.output_video).delete()
    outline = VideoOutline.objects.create(video=cocreate.output_video)
    asections = cocreate.available_sections
    for i in xrange(len(asections)):
        outline.videooutlinepin_set.create(text=asections[i],
                                           current_time=Decimal(str(i)))

    # enqueue on cocreate task queue
    enqueue_cocreate(cocreate)
Esempio n. 5
0
 def post(self, request):
     name = request.data.get("name")
     reason = request.data.get("reason")
     src = request.data.get("src")
     newVid = Video(name=name, reason=reason, src=src)
     newVid.save()
     response = Response(status=status.HTTP_200_OK)
     return response
Esempio n. 6
0
def save_video(url, languages):
    client = coreapi.Client()
    normalized_url = query_string_remove(url)
    schema = client.get(normalized_url)

    soup = BeautifulSoup(schema, "html.parser")
    video_meta_unprocessed = soup.find("div",
                                       attrs={
                                           "itemscope":
                                           True,
                                           "itemtype":
                                           "https://schema.org/VideoObject"
                                       })
    video_meta = BeautifulSoup(str(video_meta_unprocessed), "html.parser")

    duration = video_meta.find("meta", attrs={"itemprop":
                                              "duration"})["content"]
    license_url = video_meta.find("link", attrs={"itemprop":
                                                 "license"})["href"]
    title = video_meta.find("meta", attrs={"itemprop": "name"})["content"]
    description = video_meta.find("meta", attrs={"itemprop":
                                                 "description"})["content"]

    script_unprocessed = str(soup.find("script", attrs={"data-spec": "q"}))
    openIndex = script_unprocessed.index('{')
    closeIndex = script_unprocessed.rindex('}')

    jsonSubstring = script_unprocessed[openIndex:closeIndex + 1]
    talk_meta = json.loads(jsonSubstring)["__INITIAL_DATA__"]

    video_id = talk_meta["current_talk"]

    url = talk_meta["url"]
    viewed_count = talk_meta["viewed_count"]
    event = talk_meta["event"]
    speakers = []
    for speaker in talk_meta["speakers"]:
        name = construct_name(speaker)
        speakers.append(name)

    video = Video(video_id=video_id,
                  duration=duration,
                  url=url,
                  license_url=license_url,
                  title=title,
                  description=description,
                  speakers=speakers,
                  event=event,
                  viewed_count=viewed_count)
    video.save()

    video_serializer = VideoSerializer(video)

    django_rq.enqueue(func=save_subtitles,
                      args=[video_id, languages],
                      retry=Retry(max=3, interval=[10, 30, 60]))

    print(video_serializer.data)
Esempio n. 7
0
 def setUp(self):
     user = User.objects.create_user(self.fake_username, self.fake_mail,
                                     self.fake_pass)
     self.user = UserProfile(user=user)
     self.user.save()
     self.video = Video(title="TITULO",
                        description="DESCRIPCION",
                        author=user)
     self.video.save()
     self.chat_room = self.user.chatroom_set.create(video=self.video)
Esempio n. 8
0
    def test_set_values(self):
        # We should re-empliment this one once we have a way to mock out the
        # vimeo API.
        url = u'http://vimeo.com/22070806'
        vt = VimeoVideoType(url)
        video = Video()
        vt.set_values(video)

        self.assertNotEqual(video.title, '')
        self.assertNotEqual(video.description, '')
Esempio n. 9
0
 def test_set_values(self, mock_get_video_info):
     video_info = google.VideoInfo('test-channel-id', 'title',
                                   'description', 100,
                                   'http://example.com/thumb.png')
     mock_get_video_info.return_value = video_info
     vt = YoutubeVideoType('http://www.youtube.com/watch?v=_ShmidkrcY0')
     video = Video()
     vt.set_values(video)
     self.assertEqual(video.title, video_info.title)
     self.assertEqual(video.description, video_info.description)
     self.assertEqual(video.duration, video_info.duration)
     self.assertEqual(video.thumbnail, video_info.thumbnail_url)
Esempio n. 10
0
    def test_get_video_info_exception(self, mock_get_video_info):
        video_info = google.VideoInfo('test-channel-id', 'title',
                                      'description', 100,
                                      'http://example.com/thumb.png')
        mock_get_video_info.side_effect = google.APIError()
        vt = YoutubeVideoType('http://www.youtube.com/watch?v=_ShmidkrcY0')
        video = Video()
        vt.set_values(video, None, None, None)

        self.assertEqual(vt.video_id, '_ShmidkrcY0')
        self.assertEqual(video.description, '')
        self.assertEqual(video.duration, None)
        self.assertEqual(video.thumbnail, '')
Esempio n. 11
0
 def test_no_changed_signals_on_initial_created(self):
     cm1 = test_utils.mock_handler(signals.title_changed)
     cm2 = test_utils.mock_handler(signals.duration_changed)
     cm3 = test_utils.mock_handler(signals.language_changed)
     with cm1 as handler1, cm2 as handler2, cm3 as handler3:
         video = Video()
         video.primary_audio_language_code = 'en'
         video.title = 'foo'
         video.duration = 123
         video.save()
     assert_equal(handler1.call_count, 0)
     assert_equal(handler2.call_count, 0)
     assert_equal(handler3.call_count, 0)
Esempio n. 12
0
    def fetch_and_save(self, after_timestamp):
        page_token = 'BEGIN'
        params = {
            'part': 'snippet',
            'maxResults': 50,
            'order': 'date',
            'q': settings.QUERY,
            'type': 'video',
            'pageToken': page_token,
            'key': self.current_api_key,
            'publishedAfter': after_timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
        }
        videos = []
        # get next page if page token available
        while page_token:
            if page_token == 'BEGIN':
                page_token = ''
            params['pageToken'] = page_token
            resp = requests.get(url=self.url, params=params, timeout=5)
            print('Visiting page', resp.status_code)
            if resp.status_code == status.HTTP_200_OK:
                items = resp.json()['items']
                # check items as page token can be present even if no results after this page
                if 'nextPageToken' in resp.json() and items:
                    page_token = resp.json()['nextPageToken']
                else:
                    page_token = ''

                for item in items:
                    data = item['snippet']
                    # response is not correct if time is near to last upload video time
                    # check for incorrect response
                    if after_timestamp.replace(tzinfo=None) >= datetime.strptime(data['publishedAt'],
                                                                                 '%Y-%m-%dT%H:%M:%S.%fZ'):
                        page_token = ''
                        break
                    videos.append(Video(
                        title=data['title'],
                        description=data['description'],
                        publish_time=data['publishedAt'],
                        thumbnail=data['thumbnails']['default']['url'],
                        channel_title=data['channelTitle']
                    ))
            elif resp.status_code == status.HTTP_403_FORBIDDEN:
                print('API key quota expired\nUsing new keys...')
                self.change_api_key()
                self.fetch_and_save(after_timestamp)

            else:
                raise Exception('could not connect to server. please check your API key')
        Video.objects.bulk_create(videos)
Esempio n. 13
0
	def test_permision_delete_no_loggin(self):
		useromar = User.objects.create_user(username="******", email="*****@*****.**", password="******")
		userfer = User.objects.create_user(username="******", email="*****@*****.**", password="******")
		useromar.save()
		userfer.save()

		video = Video(title="omar escabiado", description="omar muy escabiado", author=useromar)
		video.save()

		clientomar = Client()

		response = clientomar.get("/video/"+str(video.id)+"/delete/")

		self.assertEqual(response.status_code, 302)
Esempio n. 14
0
def importer(filename, category = "A trier", proj = "A trier 2015"):
    c = Category.objects.get_or_create(titre=category)[0]
    p = Proj.objects.get_or_create(titre=proj, category=c, image="http://cdn.wallpapersafari.com/58/12/nyHXSO.jpg")[0]
    f = open(filename)
    for x in f.read().splitlines():
        false_title = x.split('/')[-1].split('.')[-2].split('_')
        title = ' '.join(false_title)
        if len(false_title) > 1:
            title = ' '.join(false_title[1:])
        v = Video(titre=title, url=x)
        print "Creating {}, {}".format(title, x)
        v.save()
        r = Relation_proj(proj=p, video=v)
        r.save()
Esempio n. 15
0
	def test_permision_delete(self):
		userpep = User.objects.create_user(username="******", email="*****@*****.**", password="******")
		userjuan = User.objects.create_user(username="******", email="*****@*****.**", password="******")
		userpep.save()
		userjuan.save()

		video = Video(title="pepito bailando full HD 1 link MEGA", description="Video gracioso de pepito bailando, manito arriba si te gusto", author=userjuan)
		video.save()

		clientpepito = Client()
		clientpepito.login(username=userpep, password="******")

		response = clientpepito.get("/video/"+str(video.id)+"/delete/")

		self.assertEqual(response.status_code, 404)
Esempio n. 16
0
    def create(self, validated_data):
        # logged in required
        user = ContextUtils(self.context).logged_in_user()

        # create video
        video = Video(**validated_data)
        video.user = user
        video.save()

        # add video tags
        tags = TagBuilder.get_or_create_tags(validated_data['title'])
        for tag in tags:
            video.tags.add(tag)

        return video
Esempio n. 17
0
    def test_get_video_info_exception(self, mock_get_video_info):
        video_info = google.VideoInfo('test-channel-id', 'title',
                                      'description', 100,
                                      'http://example.com/thumb.png')
        mock_get_video_info.side_effect = google.APIError()
        vt = YoutubeVideoType('http://www.youtube.com/watch?v=_ShmidkrcY0')
        video = Video()
        vt.set_values(video)

        self.assertEqual(vt.video_id, '_ShmidkrcY0')
        self.assertEqual(video.description, '')
        self.assertEqual(video.duration, None)
        self.assertEqual(video.thumbnail, '')
        # since get_video_info failed, we don't know the channel id of our
        # video URL.  We should use a dummy value to make it easier to fix the
        # issue in the future
        self.assertEqual(vt.owner_username(), None)
Esempio n. 18
0
def apiFetch(f_stop):
    search_url = 'https://www.googleapis.com/youtube/v3/search'
    video_url = 'https://www.googleapis.com/youtube/v3/videos'

    search_params = {
        'part': 'snippet',
        'q': 'nobody',
        'key': settings.YOUTUBE_DATA_API_KEY,
        'order': 'date',
        'type': 'video'
    }

    r = requests.get(search_url, params=search_params)

    results = r.json()['items']

    video_ids = []
    for result in results:
        video_ids.append(result['id']['videoId'])

    query_params = {
        'key': settings.YOUTUBE_DATA_API_KEY,
        'part': 'snippet,contentDetails',
        'id': ','.join(video_ids),
        'order': 'date'
    }

    r = requests.get(video_url, params=query_params)

    results = r.json()['items']

    videos = []
    for result in results:
        videos.append(
            Video(title=result['snippet']['title'],
                  video_id=result['id'],
                  url=f'https://www.youtube.com/watch?v={ result["id"] }',
                  duration=timedelta(seconds=parse_duration(
                      result['contentDetails']['duration']).total_seconds()),
                  thumbnail=result['snippet']['thumbnails']['high']['url']))
    Video.objects.bulk_create(videos, ignore_conflicts=True)

    if not f_stop.is_set():
        threading.Timer(10, apiFetch, [f_stop]).start()
Esempio n. 19
0
def incoming_message(request):
    """
    View to receive the webhook request from slack and check for the youtube link.
    If relevant link is incoming, save the data to DB
    :param request:
    :return: Response to slack events API, 200 status and the challenge code from the request in body
    """
    request_body = json.loads(request.body.decode('utf8'))
    validate_service = SlackService()
    if validate_service.check_for_message(request_body):
        message = request_body.get('event').get('message')
        links = validate_service.retrieve_data(message)
        relevant_data = validate_service.validate_links(links)
        relevant_link_objs = [
            Video(**link) for link in relevant_data
            if Video.objects.filter(**link).count() < 1
        ]
        Video.objects.bulk_create(relevant_link_objs)
    return HttpResponse(status=200, content_type='text/plain')
Esempio n. 20
0
def save_obj_from_entry(response):
    """
    Takes response object and stores it into db
    """
    v = Video()
    v.title = response['snippet']['title']
    v.ytid = response['id']
    unique_slugify(v, v.title)
    v.published_on = isodate.parse_datetime(response['snippet']['publishedAt'])

    # get duration of video
    duration = response["contentDetails"]["duration"]
    v.duration = int(isodate.parse_duration(duration).total_seconds())

    # get description of video
    try:
        v.description = response['snippet']['description']
    except:
        pass

    # get category
    try:
        category_response = youtube_api.videoCategories().list(
            part="snippet", id=response['snippet']['categoryId']).execute()
        v.category = category_response.get("items", [])[0]['snippet']['title']
    except:
        pass

    # get thumbnail - "default"
    try:
        v.thumbnail = response['snippet']['thumbnails']['default']['url']
    except:
        pass

    # get view count
    try:
        v.views = int(response['statistics']['viewCount'])
    except:
        pass

    v.save()
    return v
Esempio n. 21
0
def upload( request ):
    video = upload_receive( request )

    instance = Video( video = video )
    instance.save()

    basename = os.path.basename( instance.video.path )
    
    file_dict = {
        'name' : basename,
        'size' : video.size,

        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,

        'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
        'deleteType': 'POST',
    }

    return UploadResponse( request, file_dict )
Esempio n. 22
0
    def create(self, request):
        data = request.data.get("data")
        copy_from = request.data.get("copy_from")

        data.pop("videos", None)
        data.pop("id", None)

        album = self.queryset.create(**data, user=request.user)

        if copy_from:
            copy_album = self.get_object(copy_from)

            if copy_album:
                videos_to_create = [
                    Video(name=v.name, youtube_id=v.youtube_id, album=album)
                    for v in copy_album.videos.all()
                ]
                videos = Video.objects.bulk_create(videos_to_create)

        serializer = self.serializer_class(album)
        return JsonResponse(serializer.data)
Esempio n. 23
0
    def _import_video(self, video_url, videoid, title, description, thumbnail,
                      videosrt):
        videoid_match = VIDEOID_RE.search(videoid)
        videoid = videoid_match.group(1)
        video_type = YoutubeVideoType(
            'http://www.youtube.com/watch?v={0}'.format(videoid))
        try:
            video_url_obj = VideoUrl.objects.get(
                url=video_type.convert_to_video_url())
            video = video_url_obj.video
        except ObjectDoesNotExist:
            video_url_obj = None
            video = Video()
            video.youtube_videoid = videoid
        video.title = title
        video.description = description
        if video_type.entry.media.duration:
            video.duration = int(video_type.entry.media.duration.seconds)
        video.thumbnail = thumbnail
        video.save()
        Action.create_video_handler(video)

        if videosrt:
            self._import_srt(video, videosrt)
        else:
            SubtitleLanguage(video=video,
                             language='en',
                             is_original=True,
                             is_forked=True).save()

        if not video_url_obj:
            video_url_obj = VideoUrl(videoid=videoid,
                                     url=video_type.convert_to_video_url(),
                                     type=video_type.abbreviation,
                                     original=True,
                                     primary=True,
                                     video=video)
            video_url_obj.save()

        self._save_alternate_url(video, video_url)
Esempio n. 24
0
def video_detail_by_url(request):
    # POST or update a video for the url defined in the body of the request

    video_link =  JSONParser().parse(request)
    client = coreapi.Client()
    normalized_url = query_string_remove(video_link["url"])
    schema = client.get(normalized_url)

    soup = BeautifulSoup(schema, "html.parser")
    video_meta_unprocessed = soup.find("div", attrs={"itemscope":True, "itemtype":"https://schema.org/VideoObject"})
    video_meta = BeautifulSoup(str(video_meta_unprocessed), "html.parser")

    duration = video_meta.find("meta", attrs={"itemprop":"duration"})["content"]
    license_url = video_meta.find("link", attrs={"itemprop":"license"})["href"]
    title = video_meta.find("meta", attrs={"itemprop":"name"})["content"]
    description = video_meta.find("meta", attrs={"itemprop":"description"})["content"]

    script_unprocessed = str(soup.find("script", attrs={"data-spec":"q"}))
    openIndex = script_unprocessed.index('{')
    closeIndex=script_unprocessed.rindex('}')

    jsonSubstring = script_unprocessed[openIndex:closeIndex + 1]
    talk_meta = json.loads(jsonSubstring)["__INITIAL_DATA__"]

    video_id = talk_meta["current_talk"]

    url = talk_meta["url"]
    viewed_count = talk_meta["viewed_count"]
    event = talk_meta["event"]
    speakers = []
    for speaker in talk_meta["speakers"]:
        name = construct_name(speaker)
        speakers.append(name)
    
    video = Video(video_id=video_id, duration=duration, url=url, license_url=license_url, title=title, description=description, speakers=speakers, event=event, viewed_count=viewed_count)
    video.save()

    video_serializer = VideoSerializer(video)
    return JsonResponse(video_serializer.data, status=status.HTTP_200_OK)
Esempio n. 25
0
    def post(self, request):
        data = request.data.get("data")
        playlist_id = request.data.get("playlist_id")

        data.pop("videos", None)
        data.pop("id", None)

        user_id = request.user.pk
        video_info = import_videos(playlist_id)
        album = Album.objects.create(**data, user=request.user)

        videos = Video.objects.bulk_create(
            list(
                map(
                    lambda vinfo: Video(
                        name=vinfo["name"],
                        youtube_id=vinfo["id"],
                        album=album,
                    ), video_info)))

        serializer = self.serializer_class(album)
        return JsonResponse(serializer.data, safe=False)
Esempio n. 26
0
def save_obj_from_entry(entry):
    """
    Takes entry(gdata) object and stores it into db
    """
    v = Video()
    v.title = entry.media.title.text
    v.ytid = getid(entry)
    unique_slugify(v, v.title)
    v.duration = int(entry.media.duration.seconds)
    v.description = entry.media.description.text
    v.published_on = get_date(entry.published.text)
    v.category = entry.media.category[0].text
    if entry.rating is not None:
        v.rating = float(entry.rating.average)
    if entry.media.thumbnail is not None:
        v.thumbnail = entry.media.thumbnail[0].url
    try:
        v.views = int(entry.statistics.view_count)
    except:
        v.views = 0
    v.save()
    return v
Esempio n. 27
0
 def check_get_download_filename(self, title, correct_filename):
     v = Video()
     v.title = title
     self.assertEquals(v.get_download_filename(), correct_filename)
Esempio n. 28
0
def upload_video(request):
    if request.method == 'POST' and request.FILES['video_file']:
        video_file = request.FILES['video_file']

        user_id = request.user

        title = request.POST['title']
        desc = request.POST['description']
        tags = request.POST['tags']
        category = request.POST['category']

        cat = VideoCategory.objects.get(id=category)
        vid = Video(video_id=1,
                    uid=user_id,
                    title=title,
                    description=desc,
                    tags=tags,
                    category=cat,
                    videofile='video_file',
                    thumb='img_output_path')
        vid.save()
        video_id = vid.pk

        vid = Video.objects.get(id=video_id)
        img_output_path = '%s/thumbnails/%s' % (settings.MEDIA_ROOT, video_id)
        img_output_path_url = '%sthumbnails/%s' % (settings.MEDIA_URL,
                                                   video_id)
        vid.video_id = video_id
        vid.videofile = video_file
        vid.save()

        duration = get_video_length(vid.videofile.path)
        pertime = duration / 20
        ff = FFmpeg(inputs={vid.videofile.path: None},
                    outputs={
                        img_output_path + '_%d.jpg':
                        ['-vf', 'fps=1/' + str(pertime), '-vframes', '20']
                    })
        ff.run()

        vid.thumb = img_output_path + '_1.jpg'
        vid.thumb_url = img_output_path_url + '_1.jpg'
        vid.duration = duration
        vid.save()

        # Proses Tagging
        list_tags = tags.split(',')
        list_tags = [i.strip().lower() for i in list_tags]

        for tg in list_tags:
            if VideoTag.objects.filter(tag=tg).exists():
                current_tag = VideoTag.objects.filter(tag=tg).first()
                current_tag.videos.add(vid)
            else:
                create_tag = VideoTag(uid=user_id, tag=tg)
                create_tag.save()
                create_tag.videos.add(vid)

        vc_list = VideoCategory.objects.all()
        context = {'vc_list': vc_list}

        #return render(request, 'upload-video.html', context)
    else:
        vc_list = VideoCategory.objects.all()
        form = VideoForm()
        context = {'form': form, 'vc_list': vc_list}
        #return render(request, 'upload-video.html', context)
    return render(request, 'upload-video.html', context)
    def handle(self, *args, **options):
        if len(args) > 2:
            raise CommandError('Too many arguments given. Provide either one or two usernames.')
        
        elif len(args) == 2:
            try:
                free_user = User(username=args[0], first_name=args[0] + '_free', last_name='User', email='*****@*****.**')
                paid_user = User(username=args[1], first_name=args[1] + '_paid', last_name='User', email='*****@*****.**')
                free_user.save()
                paid_user.save()
                self.stdout.write('Successfully created fake users using supplied usernames.\n')
            except:
                raise CommandError("Could not create users with supplied usernames. Try different usernames.")

        elif len(args) == 1:
            try:
                free_user = User(username=args[0] + '_free', first_name=args[0] + '_free', last_name='User', email='*****@*****.**')
                paid_user = User(username=args[0] + '_paid', first_name=args[0] + '_paid', last_name='User', email='*****@*****.**')
                free_user.save()
                paid_user.save()
                self.stdout.write('Successfully created fake users using the supplied username + suffixes "_free" and "_paid".\n')
            except:
                raise CommandError("Could not create users with supplied username. Try a different username.")

        elif len(args) == 0:
            try:
                free_user = User(username='******', first_name='fakeuser_free', last_name='User', email='*****@*****.**')
                paid_user = User(username='******', first_name='fakeuser_paid', last_name='User', email='*****@*****.**')
                free_user.save()
                paid_user.save()
                self.stdout.write('Successfully created fake users using default usernames.\n')
            except:
                raise CommandError("Fake users already exist. Create differently named users using 'manage.py create_test_accounts <username>'")

        free_user.set_password('password')
        paid_user.set_password('password')
        free_user.save()
        paid_user.save()

        # Set paid_user account 
        paid_level = AccountLevel.objects.get(level='Paid')
        paid_user.userprofile.account_level = paid_level
        paid_user.userprofile.save()
        
        # Create videos for free users
        for u in (free_user, paid_user):
            created_videos = ()
            
            for i in range(10):
                temp_slug = generate_slug(5)
                temp_vid = Video(uploader=u, title="Test Fake Uploads Video " + str(i), slug=temp_slug)
                temp_vid.save()
                created_videos = created_videos + (temp_vid,)
    
            #### Videos

            #Normal
            temp_vid = created_videos[0]
            temp_vid.title = "Normal private video"
            temp_vid.description = "Normal private video."
            temp_vid.save()
            
            upload_to_s3(temp_vid.slug)

            ### Expired videos, for free user
            temp_vid = created_videos[1]
            if not u == free_user:
                upload_to_s3(temp_vid.slug)
            temp_vid = created_videos[2]
            upload_to_s3(temp_vid.slug)
            temp_vid = created_videos[3]
            upload_to_s3(temp_vid.slug)

            #Expired Yesterday, created 2 days ago
            temp_vid = created_videos[1]
            temp_vid.title = "Expired the day previous to creation"
            temp_vid.description = "Expired the day previous to creation."
            temp_vid.created = datetime.datetime.now() - datetime.timedelta(days=2)
            temp_vid.save()
            if u == free_user:
                temp_vid.expired = True
                temp_vid.expiry_date = datetime.datetime.now() - datetime.timedelta(days=1)
                temp_vid.save()
                temp_vid.delete()

            #Expires Today in 4 hours
            temp_vid = created_videos[2]
            temp_vid.title = "Expires 4 hours from creation"
            temp_vid.description = "Expires 4 hours from creation."
            if u == free_user:
                temp_vid.expiry_date = datetime.datetime.now() + datetime.timedelta(hours=4)
            temp_vid.save()

            #Expires in 3 days
            temp_vid = created_videos[3]
            temp_vid.title = "Expires 3 days from creation"
            temp_vid.description = "Expires 3 days from creation."
            if u == free_user:
                temp_vid.expiry_date = datetime.datetime.now() + datetime.timedelta(days=3)
            temp_vid.save()

            #Created Yesterday
            temp_vid = created_videos[4]
            upload_to_s3(temp_vid.slug)
            temp_vid.created = datetime.datetime.now() - datetime.timedelta(days=1)
            temp_vid.title = "Time-stamped as created the day previous to actual creation"
            temp_vid.description = "Time-stamped as created the day previous to actual creation."
            temp_vid.save()

            #Created A Week Previous
            temp_vid = created_videos[5]
            upload_to_s3(temp_vid.slug)
            temp_vid.created = datetime.datetime.now() - datetime.timedelta(days=7)
            temp_vid.title = "Time-stamped as created a week previous to actual creation"
            temp_vid.description = "Time-stamped as created a week previous to actual creation."
            temp_vid.save()

            #Public
            temp_vid = created_videos[6]
            upload_to_s3(temp_vid.slug)
            temp_vid.is_public = True
            temp_vid.title = "Public."
            temp_vid.description = "Public."
            temp_vid.save()

            #Public. Expired Yesterday, created 2 days ago
            temp_vid = created_videos[7]
            upload_to_s3(temp_vid.slug)
            temp_vid.title = "Public. Expired the day previous to creation"
            temp_vid.description = "Public. Expired the day previous to creation."
            temp_vid.is_public = True
            temp_vid.created = datetime.datetime.now() - datetime.timedelta(days=2)
            if u == free_user:
                temp_vid.expired = True
                temp_vid.expiry_date = datetime.datetime.now() - datetime.timedelta(days=1)
            temp_vid.save()

            #Outlined
            temp_vid = created_videos[8]
            upload_to_s3(temp_vid.slug)
            temp_vid.title = "Outlined"
            temp_vid.description = "Outlined."
            temp_vid.save()
            outline = VideoOutline(video=temp_vid)
            outline.save()
            outline_pin = VideoOutlinePin(video_outline=outline, text="Start")
            outline_pin.save()

            #Transferred to Youtube, created 2 days ago, deleted from server yesterday
            temp_vid = created_videos[9]
            upload_to_s3(temp_vid.slug)
            temp_vid.youtube_embed_url= "http://www.youtube.com/embed/yc5W-AClSlI"
            temp_vid.created = datetime.datetime.now() - datetime.timedelta(days=2)
            temp_vid.youtube_video_expiry_date = datetime.datetime.now() - datetime.timedelta(days=1)
            temp_vid.title = "YouTube video"
            temp_vid.description = "YouTube video."
            temp_vid.save()

        self.stdout.write('Successfully created videos!\n')
Esempio n. 30
0
            'video_id':
            item['contentDetails']['videoId'],
            'published_at':
            item['contentDetails']['videoPublishedAt']
        })

for video in videos:
    video['description'] = video['description'].replace('\n', '<br>')
    print(' # [' + video['title'] + '] ' + video['published_at'] + ' ' +
          video['video_id'] + ' ' + video['thumbnail_medium'])

print(' # TOTAL NUMBER: ' + str(len(videos)))

category = Category.objects.get(url=CATEGORY_URL)

count = 0
for v in videos:
    video = Video(category=category,
                  video_id=v['video_id'],
                  title=v['title'],
                  thumbnail_medium=v['thumbnail_medium'],
                  published_at=v['published_at'],
                  description=v['description'])
    video.save()

    count += 1
    print(' # Video added: (' + str(video.pk) + ') ' + video.title)

print(' # FINISHED!')
print('Added ' + str(count) + ' videos.')