Esempio n. 1
0
 /**
  * Handle the event.
  *
  * @param  \App\Events\WechatUserSubscribed  $event
  * @return \App\Models\Message
  */
 public function handle(WechatUserSubscribed $event)
 {
     $m = $event->message;
     /**
      * openId is always unique to our official account, so if user subscribes
      * again, we just need to toggle un-subscribed flag.
      */
     if ($subscriber = Subscriber::where('openId', $m->fromUserName)->where('unsubscribed', true)->first()) {
         $subscriber->unsubscribed = false;
     } else {
         $subscriber = new Subscriber();
         $subscriber->openId = $m->fromUserName;
     }
     $subscriber->save();
     // Link profile with subscriber if subscribe comes from profile page.
     if ($key = $m->messageable->eventKey) {
         Profile::find(Str::substr($key, Str::length('qrscene_')))->update(['weixin' => $m->fromUserName]);
         event(new ChangeSubscriberGroup($subscriber));
     }
     return $this->greetMessage($m->fromUserName, !is_null($key));
 }
Esempio n. 2
0
 /**
  * Adds % wildcards to the given string.
  *
  * @param string $str
  * @param bool $lowercase
  * @return string
  */
 public function wildcardLikeString($str, $lowercase = true)
 {
     $wild = '%';
     $length = Str::length($str);
     if ($length) {
         for ($i = 0; $i < $length; $i++) {
             $wild .= $str[$i] . '%';
         }
     }
     if ($lowercase) {
         $wild = Str::lower($wild);
     }
     return $wild;
 }
Esempio n. 3
0
 protected function prepareRequest($request, array &$options)
 {
     $method = $request->getMethod();
     $uri = $request->getUri();
     $basePath = $options['base_uri']->getPath();
     $path = Str::substr($uri->getPath(), Str::length($basePath));
     if ($method === 'GET') {
         parse_str($uri->getQuery(), $options['query']);
     } else {
         $body = (string) $request->getBody();
         $options['json'] = json_decode($body, true);
     }
     return [$method, $path];
 }
use Illuminate\Support\Str;
if (!Str::hasMacro('after')) {
    /**
     * Get the part of haystack after needle.
     *
     * @param string $haystack
     * @param string $needle
     * @return string
     */
    Str::macro('after', function ($haystack, $needle) {
        $pos = strpos($haystack, $needle);
        if ($pos === false) {
            return $haystack;
        }
        return Str::substr($haystack, $pos + Str::length($needle));
    });
}
if (!Str::hasMacro('before')) {
    /**
     * Get the part of haystack before needle.
     *
     * @param string $haystack
     * @param string $needle
     * @return string
     */
    Str::macro('before', function ($haystack, $needle) {
        $pos = strpos($haystack, $needle);
        if ($pos === false) {
            return $haystack;
        }
Esempio n. 5
0
 /**
  * Limits HTML with specific length with a proper tag handling.
  * @param string $html HTML string to limit
  * @param int $maxLength String length to truncate at
  * @param  string  $end
  * @return string
  */
 public static function limitHtml($html, $maxLength, $end = '...')
 {
     $printedLength = 0;
     $position = 0;
     $tags = array();
     $re = '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\\x80-\\xFF][\\x80-\\xBF]*}';
     $result = '';
     while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position)) {
         list($tag, $tagPosition) = $match[0];
         $str = mb_substr($html, $position, $tagPosition - $position);
         if ($printedLength + StrHelper::length($str) > $maxLength) {
             $result .= mb_substr($str, 0, $maxLength - $printedLength) . $end;
             $printedLength = $maxLength;
             break;
         }
         $result .= $str;
         $printedLength += StrHelper::length($str);
         if ($printedLength >= $maxLength) {
             $result .= $end;
             break;
         }
         if ($tag[0] == '&' || ord($tag) >= 0x80) {
             $result .= $tag;
             $printedLength++;
         } else {
             $tagName = $match[1][0];
             if ($tag[1] == '/') {
                 $openingTag = array_pop($tags);
                 $result .= $tag;
             } else {
                 if ($tag[StrHelper::length($tag) - 2] == '/') {
                     $result .= $tag;
                 } else {
                     $result .= $tag;
                     $tags[] = $tagName;
                 }
             }
         }
         $position = $tagPosition + StrHelper::length($tag);
     }
     if ($printedLength < $maxLength && $position < StrHelper::length($html)) {
         $result .= substr($html, $position, $maxLength - $printedLength);
     }
     while (!empty($tags)) {
         $result .= sprintf('</%s>', array_pop($tags));
     }
     return $result;
 }
Esempio n. 6
0
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function handle()
 {
     pcntl_signal(SIGINT, [$this, 'handleInterrupt']);
     $mlpmaPath = Config::get('ponyfm.files_directory') . '/mlpma';
     $tmpPath = Config::get('ponyfm.files_directory') . '/tmp';
     if (!File::exists($tmpPath)) {
         File::makeDirectory($tmpPath);
     }
     $UNKNOWN_GENRE = Genre::firstOrCreate(['name' => 'Unknown', 'slug' => 'unknown']);
     $this->comment('Enumerating MLP Music Archive source files...');
     $files = File::allFiles($mlpmaPath);
     $this->info(sizeof($files) . ' files found!');
     $this->comment('Enumerating artists...');
     $artists = File::directories($mlpmaPath);
     $this->info(sizeof($artists) . ' artists found!');
     $this->comment('Importing tracks...');
     $totalFiles = sizeof($files);
     $fileToStartAt = (int) $this->option('startAt') - 1;
     $this->comment("Skipping {$fileToStartAt} files..." . PHP_EOL);
     $files = array_slice($files, $fileToStartAt);
     $this->currentFile = $fileToStartAt;
     foreach ($files as $file) {
         $this->currentFile++;
         pcntl_signal_dispatch();
         if ($this->isInterrupted) {
             break;
         }
         $this->comment('[' . $this->currentFile . '/' . $totalFiles . '] Importing track [' . $file->getFilename() . ']...');
         if (in_array($file->getExtension(), $this->ignoredExtensions)) {
             $this->comment('This is not an audio file! Skipping...' . PHP_EOL);
             continue;
         }
         // Has this track already been imported?
         $importedTrack = DB::table('mlpma_tracks')->where('filename', '=', $file->getFilename())->first();
         if ($importedTrack) {
             $this->comment('This track has already been imported! Skipping...' . PHP_EOL);
             continue;
         }
         //==========================================================================================================
         // Extract the original tags.
         //==========================================================================================================
         $getId3 = new getID3();
         // all tags read by getID3, including the cover art
         $allTags = $getId3->analyze($file->getPathname());
         // tags specific to a file format (ID3 or Atom), pre-normalization but with cover art removed
         $rawTags = [];
         // normalized tags used by Pony.fm
         $parsedTags = [];
         if (Str::lower($file->getExtension()) === 'mp3') {
             list($parsedTags, $rawTags) = $this->getId3Tags($allTags);
         } elseif (Str::lower($file->getExtension()) === 'm4a') {
             list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
         } elseif (Str::lower($file->getExtension()) === 'ogg') {
             list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
         } elseif (Str::lower($file->getExtension()) === 'flac') {
             list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
         } elseif (Str::lower($file->getExtension()) === 'wav') {
             list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
         }
         //==========================================================================================================
         // Determine the release date.
         //==========================================================================================================
         $modifiedDate = Carbon::createFromTimeStampUTC(File::lastModified($file->getPathname()));
         $taggedYear = $parsedTags['year'];
         $this->info('Modification year: ' . $modifiedDate->year);
         $this->info('Tagged year: ' . $taggedYear);
         if ($taggedYear !== null && $modifiedDate->year === $taggedYear) {
             $releasedAt = $modifiedDate;
         } elseif ($taggedYear !== null && Str::length((string) $taggedYear) !== 4) {
             $this->error('This track\'s tagged year makes no sense! Using the track\'s last modified date...');
             $releasedAt = $modifiedDate;
         } elseif ($taggedYear !== null && $modifiedDate->year !== $taggedYear) {
             $this->error('Release years don\'t match! Using the tagged year...');
             $releasedAt = Carbon::create($taggedYear);
         } else {
             // $taggedYear is null
             $this->error('This track isn\'t tagged with its release year! Using the track\'s last modified date...');
             $releasedAt = $modifiedDate;
         }
         // This is later used by the classification/publishing script to determine the publication date.
         $parsedTags['released_at'] = $releasedAt->toDateTimeString();
         //==========================================================================================================
         // Does this track have vocals?
         //==========================================================================================================
         $isVocal = $parsedTags['lyrics'] !== null;
         //==========================================================================================================
         // Fill in the title tag if it's missing.
         //==========================================================================================================
         if (!$parsedTags['title']) {
             $parsedTags['title'] = $file->getBasename('.' . $file->getExtension());
         }
         //==========================================================================================================
         // Determine the genre.
         //==========================================================================================================
         $genreName = $parsedTags['genre'];
         $genreSlug = Str::slug($genreName);
         $this->info('Genre: ' . $genreName);
         if ($genreName && $genreSlug !== '') {
             $genre = Genre::where('name', '=', $genreName)->first();
             if ($genre) {
                 $genreId = $genre->id;
             } else {
                 $genre = new Genre();
                 $genre->name = $genreName;
                 $genre->slug = $genreSlug;
                 $genre->save();
                 $genreId = $genre->id;
                 $this->comment('Created a new genre!');
             }
         } else {
             $genreId = $UNKNOWN_GENRE->id;
             // "Unknown" genre ID
         }
         //==========================================================================================================
         // Determine which artist account this file belongs to using the containing directory.
         //==========================================================================================================
         $this->info('Path to file: ' . $file->getRelativePath());
         $path_components = explode(DIRECTORY_SEPARATOR, $file->getRelativePath());
         $artist_name = $path_components[0];
         $album_name = array_key_exists(1, $path_components) ? $path_components[1] : null;
         $this->info('Artist: ' . $artist_name);
         $this->info('Album: ' . $album_name);
         $artist = User::where('display_name', '=', $artist_name)->first();
         if (!$artist) {
             $artist = new User();
             $artist->display_name = $artist_name;
             $artist->email = null;
             $artist->is_archived = true;
             $artist->slug = Str::slug($artist_name);
             $slugExists = User::where('slug', '=', $artist->slug)->first();
             if ($slugExists) {
                 $this->error('Horsefeathers! The slug ' . $artist->slug . ' is already taken!');
                 $artist->slug = $artist->slug . '-' . Str::random(4);
             }
             $artist->save();
         }
         //==========================================================================================================
         // Extract the cover art, if any exists.
         //==========================================================================================================
         $this->comment('Extracting cover art!');
         $coverId = null;
         if (array_key_exists('comments', $allTags) && array_key_exists('picture', $allTags['comments'])) {
             $image = $allTags['comments']['picture'][0];
             if ($image['image_mime'] === 'image/png') {
                 $extension = 'png';
             } elseif ($image['image_mime'] === 'image/jpeg') {
                 $extension = 'jpg';
             } elseif ($image['image_mime'] === 'image/gif') {
                 $extension = 'gif';
             } else {
                 $this->error('Unknown cover art format!');
             }
             // write temporary image file
             $imageFilename = $file->getFilename() . ".cover.{$extension}";
             $imageFilePath = "{$tmpPath}/" . $imageFilename;
             File::put($imageFilePath, $image['data']);
             $imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']);
             $cover = Image::upload($imageFile, $artist);
             $coverId = $cover->id;
         } else {
             $this->comment('No cover art found!');
         }
         //==========================================================================================================
         // Is this part of an album?
         //==========================================================================================================
         $albumId = null;
         $albumName = $parsedTags['album'];
         if ($albumName !== null) {
             $album = Album::where('user_id', '=', $artist->id)->where('title', '=', $albumName)->first();
             if (!$album) {
                 $album = new Album();
                 $album->title = $albumName;
                 $album->user_id = $artist->id;
                 $album->cover_id = $coverId;
                 $album->save();
             }
             $albumId = $album->id;
         }
         //==========================================================================================================
         // Save this track.
         //==========================================================================================================
         // "Upload" the track to Pony.fm
         $this->comment('Transcoding the track!');
         Auth::loginUsingId($artist->id);
         $trackFile = new UploadedFile($file->getPathname(), $file->getFilename(), $allTags['mime_type']);
         Input::instance()->files->add(['track' => $trackFile]);
         $upload = new UploadTrackCommand(true, true);
         $result = $upload->execute();
         if ($result->didFail()) {
             $this->error(json_encode($result->getMessages(), JSON_PRETTY_PRINT));
         } else {
             // Save metadata.
             $track = Track::find($result->getResponse()['id']);
             $track->title = $parsedTags['title'];
             $track->cover_id = $coverId;
             $track->album_id = $albumId;
             $track->genre_id = $genreId;
             $track->track_number = $parsedTags['track_number'];
             $track->released_at = $releasedAt;
             $track->description = $parsedTags['comments'];
             $track->is_downloadable = true;
             $track->lyrics = $parsedTags['lyrics'];
             $track->is_vocal = $isVocal;
             $track->license_id = 2;
             $track->save();
             // If we made it to here, the track is intact! Log the import.
             DB::table('mlpma_tracks')->insert(['track_id' => $result->getResponse()['id'], 'path' => $file->getRelativePath(), 'filename' => $file->getFilename(), 'extension' => $file->getExtension(), 'imported_at' => Carbon::now(), 'parsed_tags' => json_encode($parsedTags), 'raw_tags' => json_encode($rawTags)]);
         }
         echo PHP_EOL . PHP_EOL;
     }
 }
 public function testStringQuickRandom()
 {
     $str1 = Str::quickRandom();
     $str2 = Str::length($str1);
     $this->assertEquals($str2, 16);
     $str1 = Str::quickRandom(3);
     $str2 = Str::length($str1);
     $this->assertEquals($str2, 3);
 }
Esempio n. 8
0
 /**
  * Return the length of the given string
  **/
 public function length()
 {
     return Str::length($this->value);
 }
Esempio n. 9
0
 /**
  * Return the length of the given string.
  *
  * @return int
  */
 public function length()
 {
     return Str::length($this->string);
 }
Esempio n. 10
0
 /**
  * Parses a potentially-partial date string into a proper date object.
  *
  * The tagging formats we deal with base their date format on ISO 8601, but
  * the timestamp may be incomplete.
  *
  * @link https://code.google.com/p/mp4v2/wiki/iTunesMetadata
  * @link https://wiki.xiph.org/VorbisComment#Date_and_time
  * @link http://id3.org/id3v2.4.0-frames
  *
  * @param string $dateString
  * @return null|Carbon
  */
 protected function parseDateString(string $dateString)
 {
     switch (Str::length($dateString)) {
         // YYYY
         case 4:
             return Carbon::createFromFormat('Y', $dateString)->month(1)->day(1);
             // YYYY-MM
         // YYYY-MM
         case 7:
             return Carbon::createFromFormat('Y-m', $dateString)->day(1);
             // YYYY-MM-DD
         // YYYY-MM-DD
         case 10:
             return Carbon::createFromFormat('Y-m-d', $dateString);
             break;
         default:
             // We might have an ISO-8601 string in our hooves.
             // If not, give up.
             try {
                 return Carbon::createFromFormat(Carbon::ISO8601, $dateString);
             } catch (\InvalidArgumentException $e) {
                 return null;
             }
     }
 }