Get-Fap.psm1

<#
.SYNOPSIS
Upload to fapping
 
.DESCRIPTION
This is a PowerShell script that allows you to upload images to fapping. The module takes in a number of parameters such as the image file name, format of the links, output directory for the text file, and more. The parameters are all optional except for the image file name and format. The script outputs the links to the image on the website in the specified format.
 
The script also includes a number of additional features such as the ability to create a shortcut in the send-to menu for the script, delete a shortcut from the send-to menu, and resize the images.
 
-help (-h)
     
    Display this help message and exit.
 
-args
 
    Any compatible image file under 5000kb (.gif, .jpg, .jpeg, .png)
 
-format (-f)
 
    b - Gets BBCODE-FULL links
         
        Get-Fap file.png -format b
 
    d - Gets DIRECT image links
         
        Get-Fap file.png -format d
     
    h - Gets BBCODE-THUMBS links
         
        Get-Fap file.png -format h
 
    i - Gets IMGNM links
         
        Get-Fap file.png -format i
 
    t - Gets THUMBS links
         
        Get-Fap file.png -format t
 
-resize (-r)
     
    Resize images to the desired width, accepts integers only
 
        Get-Fap file.jpg -resize 400
 
-clip (-c)
     
    Outputs the links to the clipboard
         
        Get-Fap file.jpg -clip
 
-single (-s)
     
    Outputs all links as a string with no new lines
 
        Get-Fap file.jpg -single
 
-json (-j)
    
    Outputs the links to a json file, saved to working directory if -out is not used.
     
    File will have default name 'Links - yyyy.mm.dd - HH-mm-ss.json' if none given.
 
        Get-Fap file.jpg -json
 
-txt (-t)
    
    Outputs the links to a text file, saved to working directory if -out is not used.
     
    File will have default name 'Links - yyyy.mm.dd - HH-mm-ss.txt' if none given.
 
        Get-Fap file.jpg -txt
 
-out (-o)
    
    Outputs the links to specified file or folder.
 
        Get-Fap file.jpg -txt -out C:\Mylinks.txt
 
-noexit (-n)
    
    Prompts the user for input before exiting.
 
        Get-Fap file.jpg -txt -out C:\Mylinks.txt -noexit
 
-mkshortcut (-m) (Windows only)
     
    Prompts user to create a shortcut with desired command and name in the sendto menu.
         
        Get-Fap -mkshortcut
 
-delshortcut (-d) (Windows only)
     
    Deletes shortcut from sendto menu. (Can be done manually as well through file manager)
         
        Get-Fap -delshortcut
 
.EXAMPLE
    Upload an image in bbcode-full format, output the link in the console and send it to the clipboard.
         
        Get-Fap file.jpg -format b -clip
 
.EXAMPLE
    Upload multiple images in multiple formats to the console, the clipboard and to a text file in chosen folder.
         
        Get-Fap file.jpg, file2.jpg -format b,d,h,i,t -clip -txt -out c:\
 
.EXAMPLE
    Upload multiple images in bb-thumbs format and output links on a single line.
         
        Get-Fap file.jpg, file2.jpg -format h -single
 
.EXAMPLE
    Upload image in direct format and resize to 400px (width).
         
        Get-Fap file.jpg -format d -resize 400
 
.PARAMETER HELP
    Get-Help Get-Fap
 
.INPUTS
    string
 
.OUTPUTS
    clipboard, json, txt, var
 
.LINK
    https://www.powershellgallery.com/packages/Get-Fap/
#>


function get-fap {

    [cmdletbinding()]
    param (
        [validatenotnullorempty()]
        [switch]$help,
        [parameter(mandatory=$false)]
        [supportswildcards()]
        [string[]]$args,
        [parameter(mandatory=$false)]
        [validateset("b", "d", "h", "i", "t")]
        [string[]]$format,
        [parameter(mandatory=$false)]
        [validaterange(1, [int]::maxvalue)]
        [int]$resize, 
        [validatenotnullorempty()]
        [switch]$clip,
        [validatenotnullorempty()]
        [switch]$single,
        [validatenotnullorempty()]
        [switch]$json,
        [validatenotnullorempty()]
        [switch]$txt,
        [validatenotnullorempty()]
        [supportswildcards()]
        [string]$out = $pwd,
        [validatenotnullorempty()]
        [switch]$mkshortcut,
        [validatenotnullorempty()]
        [switch]$delshortcut,
        [validatenotnullorempty()]
        [switch]$noexit
    )

    if (($mkshortcut -or $delshortcut) -and ($islinux -or $ismacos)) {
        write-error "Sorry cultists and little pinguins...this feature isn't available on your OS yet.";
    } elseif ($mkshortcut) {
        $shortcommand = read-host ('Write your command for the shortcut as you would in the terminal using the $args variable' + [environment]::newline + '(ex: Get-Fap -format b $args -noexit)');
        $shortname = read-host 'Name for your shortcut';

        $expectedformat = '^Get-Fap\s.*$'

        while ([string]::isnullorwhitespace($shortcommand) -or $shortcommand -notmatch $expectedformat) {
            write-error 'Error. Command is invalid.'
            $shortcommand = read-host ('Write your command for the shortcut as you would in the terminal using the $args variable' + [environment]::newline + '(ex: Get-Fap -format b $args -noexit)');
        }

        while ([string]::isnullorwhitespace($shortname) -or $shortname -match '[^a-zA-Z0-9\-\._]') {
            write-error 'Filename missing and/or invalid.'
            $shortname = read-host 'Name for your shortcut'
        }
            
        if (!(Test-Path "$home\Documents\PowerShell\Modules\Get-Fap\Shortcuts\")) {
            new-item -Path "$home\Documents\PowerShell\Modules\Get-Fap\Shortcuts\" -itemtype directory -Force | out-null;
        }

        $wshshell = new-object -comobject wscript.shell;
        $shortcut = $wshshell.createshortcut("$home\AppData\Roaming\Microsoft\Windows\SendTo\$shortname.lnk"); 
        $shortcommand > "$home\Documents\PowerShell\Modules\Get-Fap\Shortcuts\$shortname.ps1" ;
        $shortcut.targetpath = "C:\Program Files\PowerShell\7\pwsh.exe";
        $shortcut.arguments = "$home\Documents\PowerShell\Modules\Get-Fap\Shortcuts\$shortname.ps1";
        $shortcut.save();

        return

    } elseif ($delshortcut) { 
        $shortname = read-host 'Name of shortcut to remove';

        If (test-path "$HOME\Documents\PowerShell\Modules\Get-Fap\Shortcuts\$shortname.ps1") {
            remove-item -literalpath "$home\Documents\PowerShell\Modules\Get-Fap\Shortcuts\$shortname.ps1" -force;
            remove-item -literalpath "$home\AppData\Roaming\Microsoft\Windows\SendTo\$shortname.lnk" -force;
            'shortcut removed';
        } else {  
            write-error 'No shortcut(s) matching the provided input.';
        }

        return                               
    }

    if(!$args -or $help) {
        get-help get-fap;
        
        return

    }

    if ($host.version.major -lt 7) {
        add-type -assemblyname system.net.http;
        add-type -assemblyname System.web;
    } 

    $images = get-childitem -literalpath $args -recurse -include *.gif, *.jpg, *.jpeg, *.png -af | sort-object | select-object -expandproperty fullname; 

    foreach ($item in $images) {
        write-host "Uploading -" ($images.indexof($item) + 1) '/' $images.count -backgroundcolor blue -foregroundcolor white -nonewline; write-host ([char]0xA0);
        write-host (split-path -path $item -leaf) -foregroundcolor white;
        $img_size = (get-item -l $item).Length

        if ($img_size -gt 5000kb) {
            write-error 'Image size too big! -'([math]::round(($img_size/1MB),2))'MB - Skipping item.';

            break

        } else {
            $url = 'https://fapping.empornium.sx/'
            [byte[]]$file = [system.io.file]::readallbytes($item);
            $stream = [system.net.http.streamcontent]::new([system.io.memorystream]::new($file));
            $content = [system.net.http.multipartformdatacontent]::new();
            $content.add($stream, 'ImageUp', [system.web.httputility]::urlencode((split-path -path $item -leaf)));
            $client = [System.Net.Http.HttpClient]::new();
    
            if ($resize) {
                
                $i = New-Object System.Drawing.Bitmap $item

                while ($i.width -lt $resize) {
                    $resize = read-host 'Please enter a value lower than the original image width for resize'
                }

                $stringheader = [system.net.http.headers.contentdispositionheadervalue]::new('form-data');
                $stringheader.name = 'resize';
                $stringcontent = [system.net.http.stringcontent]::new("$resize");
                $stringcontent.headers.contentdisposition = $stringheader;
                $content.add($stringcontent);  
            }
          
            try {
                $r = invoke-webrequest "$url`image/$((($client.postasync(($url + 'upload.php'), $content)).result.content.readasstringasync().result | convertfrom-json).image_id_public)";                
                $scode = $r.statuscode;
            } catch {
                $scode = $_.exception.response.statuscode.value__;
            }
            
            $retrycount = 2;
            
            while ($retrycount--) {
              
                if($scode -eq 200){
                        
                    break

                }

                write-error "Upload failure $scode... Retrying"
                start-sleep -s 2; 
                $r = invoke-webrequest "$url`image/$((($client.postasync(("$url" + 'upload.php'), $content)).result.content.readasstringasync().result | convertfrom-json).image_id_public)";

            }

            if ($retrycount -eq 0 -and $scode -ne 200) {
                write-error 'Upload failed - Exceeded retries'
                    
                break
            }
            
            if ($format.count -gt 1) {

                switch ($format) {
                    b {
                        if ($item -eq $item[0] -or $images.count -eq 1 -or $single) {
                            $bbcodelinks += $r.inputfields[0].value;
                        } else {
                            $bbcodelinks += [environment]::newline + $r.inputfields[0].value;
                        }
                    }
                        
                    d {
                        if ($item -eq $item[0] -or $images.count -eq 1 -or $single) {
                            $directlinks += $r.inputfields[1].value;
                        } else {
                            $directlinks += [environment]::newline + $r.inputfields[1].value;
                        }
                    }
                        
                    h {
                        if ($item -eq $item[0] -or $images.count -eq 1 -or $single) {
                            $bbthumbslinks += $r.inputfields[2].value;
                        } else {
                            $bbthumbslinks += [environment]::newline + $r.inputfields[2].value;
                        }
                    }
                        
                    i {
                        if ($item -eq $item[0] -or $images.count -eq 1 -or $single) {
                            $imgnmlinks += '[imgnm]' + $r.inputfields[1].value + '[/imgnm]';
                        } else {
                            $imgnmlinks += [environment]::newline + '[imgnm]' + $r.inputfields[1].value + '[/imgnm]';
                        }
                    }
                        
                    t {
                        if ($item -eq $item[0] -or $images.count -eq 1 -or $single) {
                            $thumbslinks += $r.inputfields[3].value;
                        } else {
                            $thumbslinks += [environment]::newline + $r.inputfields[3].value;
                        }
                    }
                }

            } else {

                switch ($format) {

                    b { 
                        $links = $r.inputfields[0].value; 
                    } 

                    d { 
                        $links = $r.inputfields[1].value; 
                    }      
        
                    h { 
                        $links = $r.inputfields[2].value; 
                    }
    
                    i { 
                        $links = '[imgnm]' + $r.inputfields[1].value + '[/imgnm]'; 
                    }
    
                    t { 
                        $links = $r.inputfields[3].value; 
                    }

                }
                    
                if ($null -eq $sb -or $images.count -eq 1 -or $single) {
                    $sb += $links;
                } else {
                    $sb += [environment]::newline + $links;
                }
                
            }    
            
        }
    
    } 

    if ($format.count -gt 1) {
            
        switch ($format) {

            b { 
                $links += [ordered]@{ 
                    BBCode_Links=$bbcodelinks; 
                } 
            }

            d { 
                $links += [ordered]@{ 
                    Direct_Links=$directlinks; 
                } 
            }

            h { 
                $links += [ordered]@{ 
                    BBThumbs_Links=$bbthumbslinks; 
                } 
            }
            
            i { 
                $links += [ordered]@{ 
                    IMGNM_Links=$imgnmlinks; 
                } 
            }

            t { 
                $links += [ordered]@{ 
                    Thumbs_Links=$thumbslinks; 
                } 
            }

        }

    }
    
    if (!([string]::isnullorempty($links))) {
               
        write-host 'Fapp it for me!' -backgroundcolor blue -foregroundcolor white -nonewline; write-host ([char]0xA0);
        $resolvedPath = Resolve-Path -Path $out -ErrorAction SilentlyContinue;

        while ($resolvedpath -eq $false) {
            $out = read-host Please enter a valid path;
            $resolvedPath = Resolve-Path -Path $out -ErrorAction SilentlyContinue;
        }
    
        if ([system.io.path]::getextension($out)) {
    
            if (split-path $out -parent) {
                $out = join-path (split-path $out -parent) (split-path $out -leafbase);
            } else {
                $out = split-path $out -leafbase;
            }
        } else {
            $out = (join-path $out ('Links - ' + (get-date -format 'yyyy.mm.dd - HH-mm-ss')));
        }
    
        if ($json) {
    
            if (test-path "$out.json" -pathtype leaf) {
                'Output file already exists!'
                new-item -path "$out.json" -value ($links | convertto-json) -confirm -force | out-null;
            } else {
                new-item -path "$out.json" -value ($links | convertto-json) -force | out-null;
            }
            
        }
    
        if ($format.count -ge 2) {

            if ($txt) {
            
                if (test-path "$out.txt" -PathType Leaf) {
                    write-error 'Output file already exists!'
                    $content = $links.getenumerator().foreach({ 
                        $_.Key, $($_.Value); 
                    }) | foreach-object { 
                        $_.Trim(); 
                    }
                    
                    $overwrite = read-host "Do you want to overwrite the existing file? (Y/N)";
                    
                    if ($overwrite -eq "Y" -or $overwrite -eq "y") {
                        set-content -Path "$out.txt" -Value $content -Force | Out-Null;
                    } else {
                        write-Host "File not overwritten.";
                    }

                } else {
                    $content = $links.getenumerator().foreach({ 
                        $_.Key, $($_.Value); 
                    }) | foreach-object { 
                        $_.Trim(); 
                    }
                    set-content -Path "$out.txt" -Value $content -Force | Out-Null;
                }
            }

            if ($clip) { 
                ($links.getenumerator().foreach({ 
                    $_.key, $($_.value);
                })).trim() | set-clipboard;      
            }

            write-output $links.getenumerator().foreach({ 
                write-host ($_.key).trim() -foregroundcolor blue;
                write-host $($_.value).trim() -foregroundcolor white;
            })
            
        } else {

            if ($clip) { 
                $sb | set-clipboard;
            }

            if ($txt) {
    
                if (test-path "$out.txt" -pathtype leaf) {
                    write-error 'Output file already exists!'
                    new-item -path "$out.txt" -value $sb -confirm -force | out-null;           
                } else {
                    new-item -path "$out.txt" -value $sb -force | out-null;
                }

            }
        
            write-output $sb

        }

    }

    if ($noexit) {
        read-host Press Enter
    }
    
}