Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
74 / 74
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
MediaModerationPhotoDNAServiceProvider
100.00% covered (success)
100.00%
74 / 74
100.00% covered (success)
100.00%
3 / 3
12
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 check
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
7
 getRequest
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2declare( strict_types=1 );
3
4namespace MediaWiki\Extension\MediaModeration\Services;
5
6use LogicException;
7use MediaWiki\Config\ServiceOptions;
8use MediaWiki\Extension\MediaModeration\PhotoDNA\IMediaModerationPhotoDNAServiceProvider;
9use MediaWiki\Extension\MediaModeration\PhotoDNA\MediaModerationPhotoDNAResponseHandler;
10use MediaWiki\Extension\MediaModeration\PhotoDNA\Response;
11use MediaWiki\FileRepo\File\ArchivedFile;
12use MediaWiki\FileRepo\File\File;
13use MediaWiki\Http\HttpRequestFactory;
14use MediaWiki\Http\MWHttpRequest;
15use MediaWiki\Json\FormatJson;
16use MediaWiki\Language\RawMessage;
17use MediaWiki\Status\StatusFormatter;
18use MediaWiki\WikiMap\WikiMap;
19use StatusValue;
20use Wikimedia\Stats\StatsFactory;
21
22/**
23 * Service for interacting with Microsoft PhotoDNA API.
24 *
25 * @see https://developer.microsoftmoderator.com/docs/services/57c7426e2703740ec4c9f4c3/operations/57c7426f27037407c8cc69e6
26 */
27class MediaModerationPhotoDNAServiceProvider implements IMediaModerationPhotoDNAServiceProvider {
28
29    use MediaModerationPhotoDNAResponseHandler;
30
31    public const CONSTRUCTOR_OPTIONS = [
32        'MediaModerationPhotoDNAUrl',
33        'MediaModerationPhotoDNASubscriptionKey',
34        'MediaModerationHttpProxy',
35    ];
36
37    private readonly string $photoDNAUrl;
38    private readonly ?string $httpProxy;
39    private readonly string $photoDNASubscriptionKey;
40
41    public function __construct(
42        ServiceOptions $options,
43        private readonly HttpRequestFactory $httpRequestFactory,
44        private readonly StatsFactory $statsFactory,
45        private readonly MediaModerationImageContentsLookup $mediaModerationImageContentsLookup,
46        private readonly StatusFormatter $statusFormatter,
47    ) {
48        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
49        $this->photoDNAUrl = $options->get( 'MediaModerationPhotoDNAUrl' );
50        $this->photoDNASubscriptionKey = $options->get( 'MediaModerationPhotoDNASubscriptionKey' );
51        $this->httpProxy = $options->get( 'MediaModerationHttpProxy' );
52    }
53
54    /** @inheritDoc */
55    public function check( $file ): StatusValue {
56        $requestStatus = $this->getRequest( $file );
57        if ( !$requestStatus->isGood() ) {
58            return $requestStatus;
59        }
60        /** @var MWHttpRequest $request */
61        $request = $requestStatus->getValue();
62        $start = microtime( true );
63        $status = $request->execute();
64        $delay = microtime( true ) - $start;
65        $wiki = WikiMap::getCurrentWikiId();
66        $this->statsFactory->withComponent( 'MediaModeration' )
67            ->getTiming( 'photo_dna_request_time' )
68            ->setLabel( 'wiki', $wiki )
69            ->observeSeconds( $delay );
70        $this->statsFactory->withComponent( 'MediaModeration' )
71            ->getCounter( 'photo_dna_http_status_code_total' )
72            ->setLabel( 'wiki', $wiki )
73            ->setLabel( 'status_code', strval( $request->getStatus() ) )
74            ->increment();
75        if ( !$status->isOK() ) {
76            // Something went badly wrong.
77            $errorMessage = FormatJson::decode( $request->getContent(), true );
78            if ( is_array( $errorMessage ) && isset( $errorMessage['message'] ) ) {
79                $errorMessage = $errorMessage['message'];
80            } else {
81                $errorMessage = 'Unable to get JSON in response from PhotoDNA';
82            }
83            $this->statsFactory->withComponent( 'MediaModeration' )
84                ->getCounter( 'photo_dna_response_parse_error_total' )
85                ->setLabel( 'wiki', $wiki )
86                ->increment();
87
88            return StatusValue::newFatal(
89                new RawMessage(
90                    'PhotoDNA returned HTTP ' . $request->getStatus() . ' error: ' . $errorMessage
91                )
92            );
93        }
94        $rawResponse = $request->getContent();
95        $jsonParseStatus = FormatJson::parse( $rawResponse, FormatJson::FORCE_ASSOC );
96        $responseJson = $jsonParseStatus->getValue();
97        if ( !$jsonParseStatus->isOK() || !is_array( $responseJson ) ) {
98            $this->statsFactory->withComponent( 'MediaModeration' )
99                ->getCounter( 'photo_dna_response_parse_error_total' )
100                ->setLabel( 'wiki', $wiki )
101                ->increment();
102            return StatusValue::newFatal( new RawMessage(
103                'PhotoDNA returned an invalid JSON body for ' . $file->getName() . '. Parse error: ' .
104                $this->statusFormatter->getWikiText( $jsonParseStatus )
105            ) );
106        }
107        $response = Response::newFromArray( $responseJson, $rawResponse );
108        $this->statsFactory->withComponent( 'MediaModeration' )
109            ->getCounter( 'photo_dna_status_code_total' )
110            ->setLabel( 'wiki', $wiki )
111            ->setLabel( 'status_code', strval( $response->getStatusCode() ) )
112            ->increment();
113        return $this->createStatusFromResponse( $response );
114    }
115
116    /**
117     * @param File|ArchivedFile $file
118     * @return StatusValue
119     */
120    private function getRequest( $file ): StatusValue {
121        if ( !$this->photoDNASubscriptionKey ) {
122            throw new LogicException( '$wgMediaModerationPhotoDNASubscriptionKey API key is not set' );
123        }
124
125        $imageContentsStatus = $this->mediaModerationImageContentsLookup->getImageContents( $file );
126        if ( !$imageContentsStatus->isOK() ) {
127            // Hide the thumbnail contents and mime type from the caller of ::getRequest by
128            // creating a standard StatusValue and merging the ImageContentsStatus into it.
129            // This is done as these values will be null if we have reached here.
130            return StatusValue::newGood()->merge( $imageContentsStatus );
131        }
132        $options = [
133            'method' => 'POST',
134            'postData' => $imageContentsStatus->getImageContents(),
135            'userAgent' => $this->httpRequestFactory->getUserAgent() . ' MediaModeration-PhotoDNA',
136        ];
137        if ( $this->httpProxy ) {
138            $options['proxy'] = $this->httpProxy;
139        }
140        $request = $this->httpRequestFactory->create(
141            $this->photoDNAUrl,
142            $options,
143            __METHOD__
144        );
145        $request->setHeader( 'Content-Type', $imageContentsStatus->getMimeType() );
146        $request->setHeader( 'Ocp-Apim-Subscription-Key', $this->photoDNASubscriptionKey );
147        return StatusValue::newGood( $request );
148    }
149}