CCMain.m 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCAutoUpload.h"
  35. #import "NCBridgeSwift.h"
  36. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate>
  37. {
  38. tableMetadata *_metadata;
  39. BOOL _isRoot;
  40. BOOL _isViewDidLoad;
  41. BOOL _isOfflineServerUrl;
  42. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_depth;
  68. NSString *_noFilesSearchTitle;
  69. NSString *_noFilesSearchDescription;
  70. NSTimer *_timerWaitInput;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. BOOL _loadingFolder;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  105. _statusSwipeCell = [NSMutableDictionary new];
  106. _queueSelector = [NSMutableArray new];
  107. _sectionDataSource = [CCSectionDataSourceMetadata new];
  108. _isViewDidLoad = YES;
  109. _fatherPermission = @"";
  110. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  111. _searchResultMetadatas = [NSMutableArray new];
  112. _searchFileName = @"";
  113. _depth = @"infinity";
  114. _noFilesSearchTitle = @"";
  115. _noFilesSearchDescription = @"";
  116. // delegate
  117. self.tableView.delegate = self;
  118. self.tableView.tableFooterView = [UIView new];
  119. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  120. self.tableView.emptyDataSetDelegate = self;
  121. self.tableView.emptyDataSetSource = self;
  122. self.searchController.delegate = self;
  123. self.searchController.searchBar.delegate = self;
  124. [[CCNetworking sharedNetworking] settingDelegate:self];
  125. // Custom Cell
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  127. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  128. // long press recognizer TableView
  129. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  130. [self.tableView addGestureRecognizer:longPressRecognizer];
  131. // Pull-to-Refresh
  132. [self createRefreshControl];
  133. // Register for 3D Touch Previewing if available
  134. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  135. {
  136. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  137. }
  138. // Back Button
  139. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  140. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  141. // reMenu Background
  142. _reMenuBackgroundView = [[UIView alloc] init];
  143. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  144. // if this is not Main (the Main uses inizializeMain)
  145. if (_isRoot == NO && app.activeAccount.length > 0) {
  146. // Settings this folder & delegate & Loading datasource
  147. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  148. // Load Datasource
  149. [self reloadDatasource:_serverUrl];
  150. // Read (File) Folder
  151. [self readFileReloadFolder];
  152. }
  153. // Title
  154. [self setTitle];
  155. // Search
  156. self.definesPresentationContext = YES;
  157. self.searchController.searchResultsUpdater = self;
  158. self.searchController.dimsBackgroundDuringPresentation = NO;
  159. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  160. [self.searchController.searchBar sizeToFit];
  161. self.searchController.searchBar.delegate = self;
  162. // Hide Search Filed on Load
  163. self.tableView.tableHeaderView = self.searchController.searchBar;
  164. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  165. }
  166. // Apparirà
  167. - (void)viewWillAppear:(BOOL)animated
  168. {
  169. [super viewWillAppear:animated];
  170. // test
  171. if (app.activeAccount.length == 0)
  172. return;
  173. // Settings this folder & delegate & Loading datasource
  174. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  175. [[CCNetworking sharedNetworking] settingDelegate:self];
  176. // Color
  177. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  178. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  179. if (_isSelectedMode)
  180. [self setUINavigationBarSelected];
  181. else
  182. [self setUINavigationBarDefault];
  183. // If not editing mode remove _selectedFileIDs
  184. if (!self.tableView.editing)
  185. [_selectedFileIDsMetadatas removeAllObjects];
  186. // Plus Button
  187. [app plusButtonVisibile:true];
  188. }
  189. // E' arrivato
  190. - (void)viewDidAppear:(BOOL)animated
  191. {
  192. [super viewDidAppear:animated];
  193. // Test viewDidLoad
  194. if (_isViewDidLoad) {
  195. _isViewDidLoad = NO;
  196. } else {
  197. if (app.activeAccount.length > 0 && app.activeMain != self) {
  198. // Load Datasource
  199. [self reloadDatasource:_serverUrl];
  200. // Read (file) Folder
  201. [self readFileReloadFolder];
  202. }
  203. }
  204. // Active Main
  205. app.activeMain = self;
  206. // Title
  207. [self setTitle];
  208. }
  209. - (void)viewWillDisappear:(BOOL)animated
  210. {
  211. [super viewWillDisappear:animated];
  212. [self closeAllMenu];
  213. }
  214. - (void)didReceiveMemoryWarning
  215. {
  216. [super didReceiveMemoryWarning];
  217. // Dispose of any resources that can be recreated.
  218. }
  219. - (BOOL)prefersStatusBarHidden
  220. {
  221. return NO;
  222. }
  223. // detect scroll for remove keyboard in search mode
  224. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  225. {
  226. if (_isSearchMode && scrollView == self.tableView) {
  227. [self.searchController.searchBar endEditing:YES];
  228. }
  229. }
  230. - (void)changeTheming
  231. {
  232. if (self.isViewLoaded && self.view.window)
  233. [app changeTheming:self];
  234. // Refresh control
  235. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  236. // Reload Table View
  237. [self tableViewReloadData];
  238. }
  239. #pragma --------------------------------------------------------------------------------------------
  240. #pragma mark ===== Initizlize Mail =====
  241. #pragma --------------------------------------------------------------------------------------------
  242. - (void)initializeMain:(NSNotification *)notification
  243. {
  244. _directoryGroupBy = nil;
  245. _directoryOrder = nil;
  246. _dateReadDataSource = nil;
  247. // test
  248. if (app.activeAccount.length == 0)
  249. return;
  250. if ([app.listMainVC count] == 0 || _isRoot) {
  251. // This is Root
  252. _isRoot = YES;
  253. // Crypto Mode
  254. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  255. app.isCryptoCloudMode = NO;
  256. } else {
  257. app.isCryptoCloudMode = YES;
  258. }
  259. // go Home
  260. [self.navigationController popToRootViewControllerAnimated:NO];
  261. // Remove search mode
  262. [self cancelSearchBar];
  263. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  264. _isFolderEncrypted = NO;
  265. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  266. // add list
  267. [app.listMainVC setObject:self forKey:_serverUrl];
  268. // setting Networking
  269. [[CCNetworking sharedNetworking] settingDelegate:self];
  270. [[CCNetworking sharedNetworking] settingAccount];
  271. // populate shared Link & User variable
  272. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  273. if (results) {
  274. app.sharesLink = results[0];
  275. app.sharesUserAndGroup = results[1];
  276. }
  277. // Setting Theming
  278. [app settingThemingColorBrand];
  279. // Load Datasource
  280. [self reloadDatasource:_serverUrl];
  281. // Read (File) Folder
  282. [self readFileReloadFolder];
  283. // Load photo datasorce
  284. if (app.activePhotos)
  285. [app.activePhotos reloadDatasourceForced];
  286. // remove all of detail
  287. if (app.activeDetail)
  288. [app.activeDetail removeAllView];
  289. // remove all Notification Messages
  290. [app.listOfNotifications removeAllObjects];
  291. // home main
  292. app.homeMain = self;
  293. // Initializations
  294. [app applicationInitialized];
  295. } else {
  296. // reload datasource
  297. [self reloadDatasource:_serverUrl];
  298. }
  299. }
  300. #pragma --------------------------------------------------------------------------------------------
  301. #pragma mark ==== DZNEmptyDataSetSource ====
  302. #pragma --------------------------------------------------------------------------------------------
  303. /*
  304. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  305. {
  306. if(_isSearchMode)
  307. return NO;
  308. else
  309. return YES;
  310. }
  311. */
  312. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  313. {
  314. if (_loadingFolder)
  315. return NO;
  316. else
  317. return YES;
  318. }
  319. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. return [UIColor whiteColor];
  322. }
  323. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  324. {
  325. if (_isSearchMode)
  326. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  327. else
  328. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  329. }
  330. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  333. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  334. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  335. activityView.color = [NCBrandColor sharedInstance].brand;
  336. [activityView startAnimating];
  337. return activityView;
  338. }
  339. return nil;
  340. }
  341. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. NSString *text;
  344. if (_isSearchMode) {
  345. text = _noFilesSearchTitle;
  346. } else {
  347. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  348. }
  349. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  350. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  351. }
  352. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  353. {
  354. NSString *text;
  355. if (_isSearchMode) {
  356. text = _noFilesSearchDescription;
  357. } else {
  358. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  359. }
  360. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  361. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  362. paragraph.alignment = NSTextAlignmentCenter;
  363. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  364. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  365. }
  366. #pragma --------------------------------------------------------------------------------------------
  367. #pragma mark ===== Text Field =====
  368. #pragma --------------------------------------------------------------------------------------------
  369. - (void)minCharTextFieldDidChange:(UITextField *)sender
  370. {
  371. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  372. if (alertController)
  373. {
  374. UITextField *fileName = alertController.textFields.firstObject;
  375. UIAlertAction *okAction = alertController.actions.lastObject;
  376. okAction.enabled = fileName.text.length > 0;
  377. }
  378. }
  379. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  380. [textField selectAll:textField];
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== Graphic Window =====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)createRefreshControl
  386. {
  387. _refreshControl = [UIRefreshControl new];
  388. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  389. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  390. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  391. [self setRefreshControl:_refreshControl];
  392. }
  393. - (void)deleteRefreshControl
  394. {
  395. [_refreshControl endRefreshing];
  396. self.refreshControl = nil;
  397. }
  398. - (void)refreshControlTarget
  399. {
  400. [self readFolder:_serverUrl];
  401. // Actuate `Peek` feedback (weak boom)
  402. AudioServicesPlaySystemSound(1519);
  403. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  404. }
  405. - (void)setTitle
  406. {
  407. // Color text self.navigationItem.title
  408. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  409. if (_isSelectedMode) {
  410. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  411. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  412. self.navigationItem.titleView = nil;
  413. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  414. } else {
  415. // we are in home : LOGO BRAND
  416. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  417. self.navigationItem.title = nil;
  418. if ([app.reachability isReachable] == NO)
  419. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  420. else
  421. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  422. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  423. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  424. [singleTap setNumberOfTapsRequired:1];
  425. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  426. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  427. } else {
  428. self.navigationItem.title = _titleMain;
  429. }
  430. }
  431. }
  432. - (void)setUINavigationBarDefault
  433. {
  434. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  435. UIBarButtonItem *buttonMore, *buttonNotification;
  436. // =
  437. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  438. buttonMore.enabled = true;
  439. // <
  440. self.navigationController.navigationBar.hidden = NO;
  441. // Notification
  442. if ([app.listOfNotifications count] > 0) {
  443. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  444. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  445. buttonNotification.enabled = true;
  446. }
  447. if (buttonNotification)
  448. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  449. else
  450. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  451. self.navigationItem.leftBarButtonItem = nil;
  452. }
  453. - (void)setUINavigationBarSelected
  454. {
  455. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  456. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  457. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  458. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  459. self.navigationItem.leftBarButtonItem = leftButton;
  460. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  461. }
  462. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  463. {
  464. [self closeAllMenu];
  465. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  466. }];
  467. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  468. }
  469. - (void)cancelSelect
  470. {
  471. [self tableViewSelect:NO];
  472. [app.reSelectMenu close];
  473. }
  474. - (void)closeAllMenu
  475. {
  476. // close Menu
  477. [app.reSelectMenu close];
  478. [app.reMainMenu close];
  479. // Close Menu Logo
  480. [CCMenuAccount dismissMenu];
  481. }
  482. #pragma --------------------------------------------------------------------------------------------
  483. #pragma mark ===== Document Picker =====
  484. #pragma --------------------------------------------------------------------------------------------
  485. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  486. {
  487. NSLog(@"Cancelled");
  488. }
  489. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  490. {
  491. NSLog(@"Cancelled");
  492. }
  493. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  494. {
  495. documentPicker.delegate = self;
  496. [self presentViewController:documentPicker animated:YES completion:nil];
  497. }
  498. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  499. {
  500. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  501. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  502. __block NSError *error;
  503. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  504. NSString *fileName = [url lastPathComponent];
  505. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  506. NSData *data = [NSData dataWithContentsOfURL:newURL];
  507. if (data && error == nil) {
  508. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  509. // Upload File
  510. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  511. } else {
  512. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  513. }
  514. } else {
  515. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  516. }
  517. }];
  518. }
  519. }
  520. - (void)openImportDocumentPicker
  521. {
  522. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  523. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  524. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  525. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  526. documentProviderMenu.delegate = self;
  527. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  528. }
  529. #pragma --------------------------------------------------------------------------------------------
  530. #pragma mark ===== Assets Picker =====
  531. #pragma --------------------------------------------------------------------------------------------
  532. -(void)dismissFormUploadAssets
  533. {
  534. [self reloadDatasource];
  535. }
  536. - (void)openAssetsPickerController
  537. {
  538. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  539. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  540. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  541. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  542. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  543. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  544. dispatch_async(dispatch_get_main_queue(), ^{
  545. // init picker
  546. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  547. // set delegate
  548. picker.delegate = self;
  549. // to show selection order
  550. //picker.showsSelectionIndex = YES;
  551. // to present picker as a form sheet in iPad
  552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  553. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  554. // present picker
  555. [self presentViewController:picker animated:YES completion:nil];
  556. });
  557. }];
  558. }
  559. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  560. {
  561. [picker dismissViewControllerAnimated:YES completion:^{
  562. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session delegate:self];
  563. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  564. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  565. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  566. [self presentViewController:navigationController animated:YES completion:nil];
  567. }];
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  573. {
  574. // evitiamo il rimando della eventuale photo e/o video
  575. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  576. if (tableAccount.autoUpload) {
  577. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  578. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  579. }
  580. }
  581. #pragma --------------------------------------------------------------------------------------------
  582. #pragma mark ===== Create New (OpenModel) =====
  583. #pragma --------------------------------------------------------------------------------------------
  584. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  585. {
  586. UIViewController *viewController;
  587. NSString *fileName, *uuid, *fileID, *serverUrl;
  588. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  589. [self.tableView deselectRowAtIndexPath:index animated:NO];
  590. if (isnew) {
  591. fileName = nil;
  592. uuid = [CCUtility getUUID];
  593. fileID = nil;
  594. serverUrl = _serverUrl;
  595. } else {
  596. fileName = _metadata.fileName;
  597. uuid = _metadata.uuid;
  598. fileID = _metadata.fileID;
  599. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  600. }
  601. if ([tipo isEqualToString:@"cartadicredito"])
  602. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  603. if ([tipo isEqualToString:@"bancomat"])
  604. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  605. if ([tipo isEqualToString:@"contocorrente"])
  606. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  607. if ([tipo isEqualToString:@"accountweb"])
  608. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  609. if ([tipo isEqualToString:@"patenteguida"])
  610. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  611. if ([tipo isEqualToString:@"cartaidentita"])
  612. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  613. if ([tipo isEqualToString:@"passaporto"])
  614. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  615. if ([tipo isEqualToString:@"note"]) {
  616. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  617. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  618. [self presentViewController:navigationController animated:YES completion:nil];
  619. } else {
  620. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  621. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  622. [self presentViewController:navigationController animated:YES completion:nil];
  623. }
  624. }
  625. // New folder or new photo or video
  626. - (void)returnCreate:(NSInteger)type
  627. {
  628. switch (type) {
  629. /* PLAIN */
  630. case k_returnCreateFolderPlain: {
  631. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  632. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  633. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  634. }];
  635. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  636. NSLog(@"Cancel action");
  637. }];
  638. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  639. UITextField *fileName = alertController.textFields.firstObject;
  640. [self createFolder:fileName.text autoUploadDirectory:NO];
  641. }];
  642. okAction.enabled = NO;
  643. [alertController addAction:cancelAction];
  644. [alertController addAction:okAction];
  645. [self presentViewController:alertController animated:YES completion:nil];
  646. }
  647. break;
  648. case k_returnCreateFotoVideoPlain: {
  649. _isPickerCriptate = false;
  650. [self openAssetsPickerController];
  651. }
  652. break;
  653. case k_returnCreateFilePlain: {
  654. _isPickerCriptate = false;
  655. [self openImportDocumentPicker];
  656. }
  657. break;
  658. /* ENCRYPTED */
  659. case k_returnCreateFolderEncrypted: {
  660. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  661. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  662. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  663. }];
  664. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  665. NSLog(@"Cancel action");
  666. }];
  667. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  668. UITextField *fileName = alertController.textFields.firstObject;
  669. [self createFolderEncrypted:fileName.text];
  670. }];
  671. okAction.enabled = NO;
  672. [alertController addAction:cancelAction];
  673. [alertController addAction:okAction];
  674. [self presentViewController:alertController animated:YES completion:nil];
  675. }
  676. break;
  677. case k_returnCreateFotoVideoEncrypted: {
  678. _isPickerCriptate = true;
  679. [self openAssetsPickerController];
  680. }
  681. break;
  682. case k_returnCreateFileEncrypted: {
  683. _isPickerCriptate = true;
  684. [self openImportDocumentPicker];
  685. }
  686. break;
  687. /* UTILITY */
  688. case k_returnNote:
  689. [self openModel:@"note" isNew:true];
  690. break;
  691. case k_returnAccountWeb:
  692. [self openModel:@"accountweb" isNew:true];
  693. break;
  694. /* BANK */
  695. case k_returnCartaDiCredito:
  696. [self openModel:@"cartadicredito" isNew:true];
  697. break;
  698. case k_returnBancomat:
  699. [self openModel:@"bancomat" isNew:true];
  700. break;
  701. case k_returnContoCorrente:
  702. [self openModel:@"contocorrente" isNew:true];
  703. break;
  704. /* DOCUMENT */
  705. case k_returnPatenteGuida:
  706. [self openModel:@"patenteguida" isNew:true];
  707. break;
  708. case k_returnCartaIdentita:
  709. [self openModel:@"cartaidentita" isNew:true];
  710. break;
  711. case k_returnPassaporto:
  712. [self openModel:@"passaporto" isNew:true];
  713. break;
  714. }
  715. }
  716. #pragma --------------------------------------------------------------------------------------------
  717. #pragma mark ===== Save selected File =====
  718. #pragma --------------------------------------------------------------------------------------------
  719. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  720. {
  721. if (error)
  722. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  723. else
  724. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  725. }
  726. - (void)saveSelectedFiles
  727. {
  728. NSLog(@"[LOG] Start download selected files ...");
  729. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  730. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  731. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  732. for (tableMetadata *metadata in metadatas) {
  733. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  734. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  735. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  736. }
  737. }
  738. [_hud hideHud];
  739. });
  740. [self tableViewSelect:NO];
  741. }
  742. #pragma --------------------------------------------------------------------------------------------
  743. #pragma mark ===== Change Password =====
  744. #pragma --------------------------------------------------------------------------------------------
  745. - (void) loginSuccess:(NSInteger)loginType
  746. {
  747. [self readFolder:_serverUrl];
  748. }
  749. - (void)changePasswordAccount
  750. {
  751. // Brand
  752. if ([NCBrandOptions sharedInstance].use_login_web) {
  753. _loginWeb = [CCLoginWeb new];
  754. _loginWeb.delegate = self;
  755. _loginWeb.loginType = loginModifyPasswordUser;
  756. dispatch_async(dispatch_get_main_queue(), ^ {
  757. [_loginWeb presentModalWithDefaultTheme:self];
  758. });
  759. } else {
  760. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  761. _loginVC.delegate = self;
  762. _loginVC.loginType = loginModifyPasswordUser;
  763. [self presentViewController:_loginVC animated:YES completion:nil];
  764. }
  765. }
  766. #pragma mark -
  767. #pragma --------------------------------------------------------------------------------------------
  768. #pragma mark ===== Peek & Pop =====
  769. #pragma --------------------------------------------------------------------------------------------
  770. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  771. {
  772. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  773. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  774. if (metadata.thumbnailExists && !metadata.cryptated) {
  775. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  776. if (cell) {
  777. previewingContext.sourceRect = cell.frame;
  778. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  779. vc.delegate = self;
  780. vc.metadata = metadata;
  781. return vc;
  782. }
  783. }
  784. return nil;
  785. }
  786. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  787. {
  788. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  789. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  790. }
  791. #pragma mark -
  792. #pragma --------------------------------------------------------------------------------------------
  793. #pragma mark ==== External Sites ====
  794. #pragma --------------------------------------------------------------------------------------------
  795. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  796. {
  797. [[NCManageDatabase sharedInstance] deleteExternalSites];
  798. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  799. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  800. }
  801. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  802. {
  803. NSLog(@"[LOG] No External Sites found");
  804. }
  805. #pragma --------------------------------------------------------------------------------------------
  806. #pragma mark ==== Activity ====
  807. #pragma --------------------------------------------------------------------------------------------
  808. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  809. {
  810. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  811. // Reload Activity Data Source
  812. [app.activeActivity reloadDatasource];
  813. }
  814. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  815. {
  816. NSLog(@"[LOG] No Activity found");
  817. }
  818. #pragma --------------------------------------------------------------------------------------------
  819. #pragma mark ==== Notification ====
  820. #pragma --------------------------------------------------------------------------------------------
  821. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  822. {
  823. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. // Order by date
  826. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  827. OCNotifications *notification1 = obj1, *notification2 = obj2;
  828. return [notification2.date compare: notification1.date];
  829. }];
  830. // verify if listOfNotifications is changed
  831. NSString *old = @"", *new = @"";
  832. for (OCNotifications *notification in listOfNotifications)
  833. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  834. for (OCNotifications *notification in appDelegate.listOfNotifications)
  835. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  836. if (![new isEqualToString:old]) {
  837. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  838. // reload Notification view
  839. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  840. }
  841. // Update NavigationBar
  842. if (!_isSelectedMode) {
  843. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  844. }
  845. });
  846. }
  847. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  848. {
  849. // Update NavigationBar
  850. if (!_isSelectedMode)
  851. [self setUINavigationBarDefault];
  852. }
  853. - (void)viewNotification
  854. {
  855. if ([app.listOfNotifications count] > 0) {
  856. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  857. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  858. [self presentViewController:notificationVC animated:YES completion:nil];
  859. }
  860. }
  861. #pragma --------------------------------------------------------------------------------------------
  862. #pragma mark ==== User Profile ====
  863. #pragma --------------------------------------------------------------------------------------------
  864. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  865. {
  866. if (errorCode == 401)
  867. [self changePasswordAccount];
  868. }
  869. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  870. {
  871. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  872. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  873. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  874. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  875. if (avatar)
  876. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  877. else
  878. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  879. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  880. });
  881. }
  882. #pragma --------------------------------------------------------------------------------------------
  883. #pragma mark ==== Capabilities ====
  884. #pragma --------------------------------------------------------------------------------------------
  885. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  886. {
  887. // Change Theming color
  888. [app settingThemingColorBrand];
  889. if (errorCode == 401)
  890. [self changePasswordAccount];
  891. }
  892. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  893. {
  894. // Update capabilities db
  895. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  896. // ------ THEMING -----------------------------------------------------------------------
  897. // Download Theming Background & Change Theming color
  898. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  899. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  900. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  901. if (themingBackground)
  902. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  903. else
  904. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  905. }
  906. dispatch_async(dispatch_get_main_queue(), ^{
  907. [app settingThemingColorBrand];
  908. });
  909. });
  910. // ------ SEARCH ------------------------------------------------------------------------
  911. // Search bar if change version
  912. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  913. [self cancelSearchBar];
  914. }
  915. // ------ GET SERVICE SERVER ------------------------------------------------------------
  916. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  917. // Read External Sites
  918. if (capabilities.isExternalSitesServerEnabled) {
  919. metadataNet.action = actionGetExternalSitesServer;
  920. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  921. }
  922. // Read Share
  923. if (capabilities.isFilesSharingAPIEnabled) {
  924. [app.sharesID removeAllObjects];
  925. metadataNet.action = actionReadShareServer;
  926. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  927. }
  928. // Read Notification
  929. metadataNet.action = actionGetNotificationServer;
  930. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  931. // Read User Profile
  932. metadataNet.action = actionGetUserProfile;
  933. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  934. // Read Activity
  935. metadataNet.action = actionGetActivityServer;
  936. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  937. }
  938. #pragma mark -
  939. #pragma --------------------------------------------------------------------------------------------
  940. #pragma mark ==== Request Server Information ====
  941. #pragma --------------------------------------------------------------------------------------------
  942. - (void)requestServerCapabilities
  943. {
  944. // test
  945. if (app.activeAccount.length == 0)
  946. return;
  947. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  948. metadataNet.action = actionGetCapabilities;
  949. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  950. }
  951. #pragma mark -
  952. #pragma --------------------------------------------------------------------------------------------
  953. #pragma mark ==== Middleware Ping ====
  954. #pragma --------------------------------------------------------------------------------------------
  955. - (void)middlewarePing
  956. {
  957. // test
  958. if (app.activeAccount.length == 0)
  959. return;
  960. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  961. metadataNet.action = actionMiddlewarePing;
  962. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  963. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  964. }
  965. #pragma mark -
  966. #pragma --------------------------------------------------------------------------------------------
  967. #pragma mark ==== Download Thumbnail Delegate ====
  968. #pragma --------------------------------------------------------------------------------------------
  969. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  970. {
  971. __block CCCellMain *cell;
  972. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  973. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  974. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  975. cell.file.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  976. if (cell.file.image == nil) {
  977. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  978. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  979. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  980. });
  981. }
  982. }
  983. }
  984. #pragma --------------------------------------------------------------------------------------------
  985. #pragma mark ==== Download ====
  986. #pragma --------------------------------------------------------------------------------------------
  987. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  988. {
  989. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  990. // File do not exists on server, remove in local
  991. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  992. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  993. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  994. if (metadata.directory && serverUrl) {
  995. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  996. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  997. }
  998. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  999. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1000. }
  1001. if ([selector isEqualToString:selectorLoadViewImage]) {
  1002. dispatch_async(dispatch_get_main_queue(), ^{
  1003. // Updating Detail
  1004. if (app.activeDetail)
  1005. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1006. // Updating Photos
  1007. if (app.activePhotos)
  1008. [app.activePhotos downloadFileFailure:errorCode];
  1009. });
  1010. } else {
  1011. if (errorCode != kCFURLErrorCancelled)
  1012. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1013. }
  1014. [self reloadDatasource:serverUrl];
  1015. }
  1016. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1017. {
  1018. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1019. if (metadata == nil)
  1020. return;
  1021. // Download
  1022. if ([selector isEqualToString:selectorDownloadFile]) {
  1023. [self reloadDatasource:serverUrl];
  1024. }
  1025. // Synchronized
  1026. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1027. [self reloadDatasource:serverUrl];
  1028. }
  1029. // add Favorite
  1030. if ([selector isEqualToString:selectorAddFavorite]) {
  1031. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1032. }
  1033. // encrypted file
  1034. if ([selector isEqualToString:selectorEncryptFile]) {
  1035. [self encryptedFile:metadata];
  1036. }
  1037. // decrypted file
  1038. if ([selector isEqualToString:selectorDecryptFile]) {
  1039. [self decryptedFile:metadata];
  1040. }
  1041. // open View File
  1042. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1043. [self reloadDatasource:serverUrl];
  1044. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1045. selector = selectorOpenIn;
  1046. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1047. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1048. selector = selectorOpenIn;
  1049. } else {
  1050. _metadata = metadata;
  1051. if ([self shouldPerformSegue])
  1052. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1053. }
  1054. }
  1055. // addLocal
  1056. if ([selector isEqualToString:selectorAddLocal]) {
  1057. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1058. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1059. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1060. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1061. [self reloadDatasource:serverUrl];
  1062. }
  1063. // Open with...
  1064. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1065. [self reloadDatasource:serverUrl];
  1066. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1067. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1068. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1069. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1070. _docController.delegate = self;
  1071. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1072. }
  1073. // Save to Photo Album
  1074. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1075. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1076. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1077. // evitiamo il rimando photo
  1078. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1079. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1080. if (image)
  1081. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1082. else
  1083. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1084. }
  1085. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1086. // we avoid the cross-reference video
  1087. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1088. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1089. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1090. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1091. } else {
  1092. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1093. }
  1094. }
  1095. [self reloadDatasource:serverUrl];
  1096. }
  1097. // Copy File
  1098. if ([selector isEqualToString:selectorLoadCopy]) {
  1099. [self reloadDatasource:serverUrl];
  1100. [self copyFileToPasteboard:metadata];
  1101. }
  1102. // download and view a template
  1103. if ([selector isEqualToString:selectorLoadModelView]) {
  1104. // se è un template aggiorniamo anche nel FileSystem
  1105. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1106. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1107. }
  1108. [self openModel:metadata.model isNew:false];
  1109. [self reloadDatasource:serverUrl];
  1110. }
  1111. //download file plist
  1112. if ([selector isEqualToString:selectorLoadPlist]) {
  1113. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1114. long countSelectorLoadPlist = 0;
  1115. for (NSOperation *operation in [app.netQueue operations]) {
  1116. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1117. countSelectorLoadPlist++;
  1118. }
  1119. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1120. dispatch_async(dispatch_get_main_queue(), ^{
  1121. [self reloadDatasource:serverUrl];
  1122. });
  1123. }
  1124. });
  1125. }
  1126. //selectorLoadViewImage
  1127. if ([selector isEqualToString:selectorLoadViewImage]) {
  1128. // Detail
  1129. if (app.activeDetail)
  1130. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1131. // Photos
  1132. if (app.activePhotos)
  1133. [app.activePhotos downloadFileSuccess:metadata];
  1134. [self reloadDatasource:serverUrl];
  1135. }
  1136. // if exists postselector call self with selectorPost
  1137. if ([selectorPost length] > 0)
  1138. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1139. }
  1140. - (void)downloadSelectedFilesFolders
  1141. {
  1142. NSLog(@"[LOG] Start download selected ...");
  1143. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1144. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1145. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1146. for (tableMetadata *metadata in selectedMetadatas) {
  1147. if ([metadata.type isEqualToString: k_metadataType_file]) {
  1148. if (metadata.directory) {
  1149. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1150. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1151. [[CCSynchronize sharedSynchronize] synchronizedFolder:serverUrl selector:selectorReadFolderWithDownload];
  1152. } else {
  1153. [[CCSynchronize sharedSynchronize] synchronizedFile:metadata selector:selectorReadFileWithDownload];
  1154. }
  1155. }
  1156. }
  1157. [_hud hideHud];
  1158. });
  1159. [self tableViewSelect:NO];
  1160. }
  1161. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1162. {
  1163. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1164. for (tableMetadata *metadata in metadatas) {
  1165. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1166. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1167. metadataNet.action = actionDownloadFile;
  1168. metadataNet.downloadData = NO;
  1169. metadataNet.downloadPlist = YES;
  1170. metadataNet.fileID = metadata.fileID;
  1171. metadataNet.selector = selectorLoadPlist;
  1172. metadataNet.serverUrl = serverUrl;
  1173. metadataNet.session = k_download_session_foreground;
  1174. metadataNet.taskStatus = k_taskStatusResume;
  1175. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1176. //[[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selectorLoadPlist selectorPost:nil session:k_download_session_foreground taskStatus:k_taskStatusResume delegate:self];
  1177. }
  1178. }
  1179. }
  1180. #pragma --------------------------------------------------------------------------------------------
  1181. #pragma mark ===== Upload new Photos/Videos =====
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1184. {
  1185. // Auto Upload
  1186. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1187. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1188. // ONLY BACKGROUND
  1189. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1190. } else {
  1191. // ONLY FOREFROUND
  1192. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1193. }
  1194. }
  1195. // Read File test do not exists
  1196. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1197. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1198. // reUpload
  1199. if (metadata)
  1200. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1201. }
  1202. // Print error
  1203. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1204. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1205. }
  1206. [self reloadDatasource:serverUrl];
  1207. }
  1208. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1209. {
  1210. // Auto Upload
  1211. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll]) {
  1212. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1213. // ONLY BACKGROUND
  1214. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1215. } else {
  1216. // ONLY FOREFROUND
  1217. [[NCAutoUpload sharedInstance] performSelectorOnMainThread:@selector(loadAutoUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1218. }
  1219. }
  1220. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1221. [self readFolder:serverUrl];
  1222. } else {
  1223. [self reloadDatasource:serverUrl];
  1224. }
  1225. }
  1226. //
  1227. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1228. //
  1229. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1230. {
  1231. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1232. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1233. });
  1234. }
  1235. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1236. {
  1237. NSArray *assets = [arguments objectAtIndex:0];
  1238. NSString *serverUrl = [arguments objectAtIndex:1];
  1239. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1240. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1241. NSString *session = [arguments objectAtIndex:4];
  1242. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1243. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1244. // Create the folder for Photos & if request the subfolders
  1245. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1246. return;
  1247. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1248. for (PHAsset *asset in assets) {
  1249. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1250. NSDate *assetDate = asset.creationDate;
  1251. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1252. // Create serverUrl if use sub folder
  1253. if (useSubFolder) {
  1254. [formatter setDateFormat:@"yyyy"];
  1255. NSString *yearString = [formatter stringFromDate:assetDate];
  1256. [formatter setDateFormat:@"MM"];
  1257. NSString *monthString = [formatter stringFromDate:assetDate];
  1258. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1259. }
  1260. // Check if is in upload
  1261. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1262. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1263. if ([isRecordInSessions count] > 0) {
  1264. // next upload
  1265. continue;
  1266. } else {
  1267. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1268. if (cryptated) {
  1269. metadataNet.action = actionUploadAsset;
  1270. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1271. metadataNet.cryptated = cryptated;
  1272. metadataNet.fileName = fileName;
  1273. metadataNet.session = session;
  1274. metadataNet.selector = selectorUploadFile;
  1275. metadataNet.selectorPost = nil;
  1276. metadataNet.serverUrl = serverUrl;
  1277. metadataNet.taskStatus = k_taskStatusResume;
  1278. } else {
  1279. metadataNet.action = actionReadFile;
  1280. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1281. metadataNet.cryptated = cryptated;
  1282. metadataNet.fileName = fileName;
  1283. metadataNet.session = session;
  1284. metadataNet.selector = selectorReadFileUploadFile;
  1285. metadataNet.serverUrl = serverUrl;
  1286. }
  1287. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1288. }
  1289. }
  1290. }
  1291. #pragma --------------------------------------------------------------------------------------------
  1292. #pragma mark ==== Read File ====
  1293. #pragma --------------------------------------------------------------------------------------------
  1294. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1295. {
  1296. // Read Folder
  1297. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1298. //[self readFolderWithForced:NO serverUrl:metadataNet.serverUrl];
  1299. }
  1300. // UploadFile
  1301. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1302. // File not exists
  1303. if (errorCode == 404) {
  1304. metadataNet.action = actionUploadAsset;
  1305. metadataNet.errorCode = 0;
  1306. metadataNet.selector = selectorUploadFile;
  1307. metadataNet.selectorPost = nil;
  1308. metadataNet.taskStatus = k_taskStatusResume;
  1309. if ([metadataNet.session containsString:@"wwan"])
  1310. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1311. else
  1312. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1313. } else {
  1314. // error ho many retry befor notification and go to on next asses
  1315. if (metadataNet.errorRetry < 3) {
  1316. // Retry read file
  1317. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1318. } else {
  1319. // STOP check file, view message error
  1320. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1321. }
  1322. }
  1323. }
  1324. }
  1325. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1326. {
  1327. // Read Folder
  1328. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1329. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1330. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1331. [self readFolder:metadataNet.serverUrl];
  1332. }
  1333. }
  1334. // UploadFile
  1335. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1336. metadataNet.action = actionUploadAsset;
  1337. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1338. metadataNet.selector = selectorUploadFile;
  1339. metadataNet.selectorPost = nil;
  1340. metadataNet.taskStatus = k_taskStatusResume;
  1341. if ([metadataNet.session containsString:@"wwan"])
  1342. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1343. else
  1344. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1345. }
  1346. }
  1347. - (void)readFileReloadFolder
  1348. {
  1349. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1350. return;
  1351. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1352. metadataNet.action = actionReadFile;
  1353. metadataNet.priority = NSOperationQueuePriorityHigh;
  1354. metadataNet.selector = selectorReadFileReloadFolder;
  1355. metadataNet.serverUrl = _serverUrl;
  1356. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1357. }
  1358. #pragma --------------------------------------------------------------------------------------------
  1359. #pragma mark ==== Read Folder ====
  1360. #pragma --------------------------------------------------------------------------------------------
  1361. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1362. {
  1363. // verify active user
  1364. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1365. _loadingFolder = NO;
  1366. [self tableViewReloadData];
  1367. [_refreshControl endRefreshing];
  1368. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1369. if (message && [record.account isEqualToString:metadataNet.account])
  1370. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1371. [self reloadDatasource:metadataNet.serverUrl];
  1372. if (errorCode == 401)
  1373. [self changePasswordAccount];
  1374. }
  1375. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1376. {
  1377. // verify active user
  1378. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1379. if (![record.account isEqualToString:metadataNet.account])
  1380. return;
  1381. // save father e update permission
  1382. if(!_isSearchMode && metadataFolder)
  1383. _fatherPermission = metadataFolder.permissions;
  1384. NSArray *recordsInSessions;
  1385. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1386. if (_isSearchMode) {
  1387. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1388. } else {
  1389. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1390. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1391. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1392. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1393. }
  1394. for (tableMetadata *metadata in metadatas) {
  1395. // type of file
  1396. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1397. // if crypto do not insert
  1398. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1399. // verify if the record encrypted has plist + crypto
  1400. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1401. BOOL isCryptoComplete = NO;
  1402. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1403. for (tableMetadata *completeMetadata in metadatas) {
  1404. if (completeMetadata.cryptated == NO) continue;
  1405. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1406. isCryptoComplete = YES;
  1407. break;
  1408. }
  1409. }
  1410. if (isCryptoComplete == NO) continue;
  1411. }
  1412. // verify if the record is in download/upload progress
  1413. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1414. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1415. // is in Download or Upload
  1416. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1417. continue;
  1418. }
  1419. }
  1420. // Insert in Array
  1421. [metadatasToInsertInDB addObject:metadata];
  1422. }
  1423. // insert in Database
  1424. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB activeUrl:app.activeUrl serverUrl:metadataNet.serverUrl];
  1425. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1426. // read plist
  1427. if (!_isSearchMode)
  1428. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1429. // File is changed ??
  1430. if (!_isSearchMode && metadatasToInsertInDB)
  1431. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1432. });
  1433. // Search Mode
  1434. if (_isSearchMode) {
  1435. // Fix managed -> Unmanaged _searchResultMetadatas
  1436. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1437. [self reloadDatasource:metadataNet.serverUrl];
  1438. }
  1439. // this is the same directory
  1440. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1441. // reload
  1442. [self reloadDatasource:metadataNet.serverUrl];
  1443. // stoprefresh
  1444. [_refreshControl endRefreshing];
  1445. // Enable change user
  1446. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1447. _loadingFolder = NO;
  1448. [self tableViewReloadData];
  1449. }
  1450. }
  1451. - (void)readFolder:(NSString *)serverUrl
  1452. {
  1453. // init control
  1454. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1455. [_refreshControl endRefreshing];
  1456. return;
  1457. }
  1458. // Search Mode
  1459. if (_isSearchMode) {
  1460. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1461. _searchFileName = @""; // forced reload searchg
  1462. [self updateSearchResultsForSearchController:self.searchController];
  1463. return;
  1464. }
  1465. _loadingFolder = YES;
  1466. [self tableViewReloadData];
  1467. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1468. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1469. metadataNet.action = actionReadFolder;
  1470. metadataNet.date = [NSDate date];
  1471. metadataNet.directoryID = directory.directoryID;
  1472. metadataNet.priority = NSOperationQueuePriorityHigh;
  1473. metadataNet.selector = selectorReadFolder;
  1474. metadataNet.serverUrl = serverUrl;
  1475. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1476. }
  1477. #pragma mark -
  1478. #pragma --------------------------------------------------------------------------------------------
  1479. #pragma mark ===== Search =====
  1480. #pragma --------------------------------------------------------------------------------------------
  1481. -(void)searchStartTimer
  1482. {
  1483. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1484. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:_depth date:nil selector:selectorSearch delegate:self];
  1485. _noFilesSearchTitle = @"";
  1486. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1487. [self.tableView reloadEmptyDataSet];
  1488. }
  1489. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1490. {
  1491. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  1492. _isSearchMode = YES;
  1493. [self deleteRefreshControl];
  1494. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1495. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1496. _searchFileName = fileName;
  1497. // First : filter
  1498. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1499. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1500. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1501. [_searchResultMetadatas removeAllObjects];
  1502. for (tableMetadata *record in records)
  1503. [_searchResultMetadatas addObject:record];
  1504. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1505. metadataNet.account = app.activeAccount;
  1506. metadataNet.directoryID = directoryID;
  1507. metadataNet.selector = selectorSearch;
  1508. metadataNet.serverUrl = _serverUrl;
  1509. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1510. // Version >= 12
  1511. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1512. [_timerWaitInput invalidate];
  1513. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1514. }
  1515. }
  1516. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1517. [self reloadDatasource];
  1518. }
  1519. }
  1520. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1521. {
  1522. [self cancelSearchBar];
  1523. [self readFolder:_serverUrl];
  1524. }
  1525. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1526. {
  1527. _searchFileName = @"";
  1528. if (message)
  1529. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1530. }
  1531. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1532. {
  1533. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1534. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1535. }
  1536. - (void)cancelSearchBar
  1537. {
  1538. if (self.searchController.active) {
  1539. [self.searchController setActive:NO];
  1540. [self createRefreshControl];
  1541. _isSearchMode = NO;
  1542. _searchFileName = @"";
  1543. _dateReadDataSource = nil;
  1544. _searchResultMetadatas = [NSMutableArray new];
  1545. [self reloadDatasource];
  1546. }
  1547. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  1548. }
  1549. #pragma mark -
  1550. #pragma --------------------------------------------------------------------------------------------
  1551. #pragma mark ===== Delete File or Folder =====
  1552. #pragma --------------------------------------------------------------------------------------------
  1553. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1554. {
  1555. [self deleteFileOrFolderSuccess:metadataNet];
  1556. }
  1557. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1558. {
  1559. [_queueSelector removeObject:metadataNet.selector];
  1560. if ([_queueSelector count] == 0) {
  1561. [_hud hideHud];
  1562. // next
  1563. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1564. if ([_selectedFileIDsMetadatas count] > 0) {
  1565. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1566. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1567. } else {
  1568. // End Select Table View
  1569. [self tableViewSelect:NO];
  1570. // Reload
  1571. if (_isSearchMode)
  1572. [self readFolder:metadataNet.serverUrl];
  1573. else
  1574. [self reloadDatasource:metadataNet.serverUrl];
  1575. }
  1576. }
  1577. }
  1578. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1579. {
  1580. if (metadata.cryptated) {
  1581. [_queueSelector addObject:selectorDeleteCrypto];
  1582. [_queueSelector addObject:selectorDeletePlist];
  1583. } else {
  1584. [_queueSelector addObject:selectorDelete];
  1585. }
  1586. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1587. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1588. }
  1589. - (void)deleteFile
  1590. {
  1591. [_queueSelector removeAllObjects];
  1592. if ([_selectedFileIDsMetadatas count] > 0) {
  1593. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1594. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1595. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1596. } else {
  1597. _numSelectedFileIDsMetadatas = 1;
  1598. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1599. }
  1600. }
  1601. #pragma --------------------------------------------------------------------------------------------
  1602. #pragma mark ===== Rename / Move =====
  1603. #pragma --------------------------------------------------------------------------------------------
  1604. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1605. {
  1606. [self readFolder:metadataNet.serverUrl];
  1607. }
  1608. - (void)renameFile:(NSArray *)arguments
  1609. {
  1610. tableMetadata* metadata = [arguments objectAtIndex:0];
  1611. NSString *fileName = [arguments objectAtIndex:1];
  1612. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1613. }
  1614. - (void)renameNote:(NSArray *)arguments
  1615. {
  1616. tableMetadata* metadata = [arguments objectAtIndex:0];
  1617. NSString *fileName = [arguments objectAtIndex:1];
  1618. CCTemplates *templates = [[CCTemplates alloc] init];
  1619. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1620. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1621. if (fileNameModel) {
  1622. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1623. metadataNet.action = actionUploadTemplate;
  1624. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1625. metadataNet.fileNamePrint = fileName;
  1626. metadataNet.etag = metadata.etag;
  1627. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1628. metadataNet.session = k_upload_session_foreground;
  1629. metadataNet.taskStatus = k_taskStatusResume;
  1630. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1631. }
  1632. }
  1633. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1634. {
  1635. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1636. [_hud hideHud];
  1637. if (message)
  1638. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1639. // End Select Table View
  1640. [self tableViewSelect:NO];
  1641. // reload Datasource
  1642. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1643. [self readFolder:metadataNet.serverUrl];
  1644. else
  1645. [self reloadDatasource];
  1646. }
  1647. }
  1648. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1649. {
  1650. [_queueSelector removeObject:metadataNet.selector];
  1651. if ([_queueSelector count] == 0) {
  1652. [_hud hideHud];
  1653. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1654. NSString *directoryID = metadataNet.directoryID;
  1655. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1656. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1657. // FILE -> Metadata
  1658. if (metadataNet.directory == NO) {
  1659. // move metadata
  1660. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1661. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1662. }
  1663. // DIRECTORY -> Directory - CCMetadata
  1664. if (metadataNet.directory == YES) {
  1665. // delete all dir / subdir
  1666. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1667. // move metadata
  1668. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1669. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1670. // Add new directory
  1671. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1672. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1673. }
  1674. // next
  1675. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1676. if ([_selectedFileIDsMetadatas count] > 0) {
  1677. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1678. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1679. } else {
  1680. // End Select Table View
  1681. [self tableViewSelect:NO];
  1682. // reload Datasource
  1683. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1684. [self readFolder:metadataNet.serverUrl];
  1685. else
  1686. [self reloadDatasource];
  1687. }
  1688. }
  1689. }
  1690. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1691. {
  1692. tableMetadata *metadata = [arguments objectAtIndex:0];
  1693. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1694. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1695. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1696. // Plain
  1697. if (metadata.cryptated == NO) {
  1698. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1699. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1700. if(!error) {
  1701. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1702. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1703. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1704. }];
  1705. [alert addAction:ok];
  1706. [self presentViewController:alert animated:YES completion:nil];
  1707. });
  1708. // End Select Table View
  1709. [self tableViewSelect:NO];
  1710. // reload Datasource
  1711. [self readFileReloadFolder];
  1712. return;
  1713. }
  1714. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1715. metadataNet.action = actionMoveFileOrFolder;
  1716. metadataNet.directory = metadata.directory;
  1717. metadataNet.fileID = metadata.fileID;
  1718. metadataNet.directoryID = metadata.directoryID;
  1719. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1720. metadataNet.fileName = metadata.fileName;
  1721. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1722. metadataNet.fileNameTo = metadata.fileName;
  1723. metadataNet.etag = metadata.etag;
  1724. metadataNet.selector = selectorMove;
  1725. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1726. metadataNet.serverUrlTo = serverUrlTo;
  1727. [_queueSelector addObject:metadataNet.selector];
  1728. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1729. }
  1730. // cyptated
  1731. if (metadata.cryptated == YES) {
  1732. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1733. metadataNet.action = actionMoveFileOrFolder;
  1734. metadataNet.directory = metadata.directory;
  1735. metadataNet.fileID = metadata.fileID;
  1736. metadataNet.directoryID = metadata.directoryID;
  1737. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1738. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1739. metadataNet.etag = metadata.etag;
  1740. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1741. metadataNet.serverUrlTo = serverUrlTo;
  1742. // data
  1743. metadataNet.fileName = metadata.fileNameData;
  1744. metadataNet.fileNameTo = metadata.fileNameData;
  1745. metadataNet.selector = selectorMoveCrypto;
  1746. [_queueSelector addObject:metadataNet.selector];
  1747. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1748. // plist
  1749. metadataNet.fileName = metadata.fileName;
  1750. metadataNet.fileNameTo = metadata.fileName;
  1751. metadataNet.selector = selectorMovePlist;
  1752. [_queueSelector addObject:metadataNet.selector];
  1753. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1754. }
  1755. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1756. }
  1757. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1758. {
  1759. [_queueSelector removeAllObjects];
  1760. if ([_selectedFileIDsMetadatas count] > 0) {
  1761. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1762. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1763. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1764. } else {
  1765. _numSelectedFileIDsMetadatas = 1;
  1766. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1767. }
  1768. }
  1769. - (void)moveOpenWindow:(NSArray *)indexPaths
  1770. {
  1771. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1772. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1773. viewController.delegate = self;
  1774. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1775. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1776. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1777. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1778. viewController.networkingOperationQueue = app.netQueue;
  1779. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1780. [self presentViewController:navigationController animated:YES completion:nil];
  1781. }
  1782. #pragma --------------------------------------------------------------------------------------------
  1783. #pragma mark ===== Create folder =====
  1784. #pragma --------------------------------------------------------------------------------------------
  1785. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1786. {
  1787. [_hud hideHud];
  1788. if (message)
  1789. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1790. }
  1791. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1792. {
  1793. [_hud hideHud];
  1794. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1795. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1796. // Load Folder or the Datasource
  1797. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1798. [self readFolder:metadataNet.serverUrl];
  1799. } else {
  1800. [self reloadDatasource:metadataNet.serverUrl];
  1801. }
  1802. }
  1803. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1804. {
  1805. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1806. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1807. if (![fileNameFolder length]) return;
  1808. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1809. else metadataNet.serverUrl = _serverUrl;
  1810. metadataNet.action = actionCreateFolder;
  1811. if (autoUploadDirectory)
  1812. metadataNet.options = @"folderAutoUpload";
  1813. metadataNet.fileName = fileNameFolder;
  1814. metadataNet.selector = selectorCreateFolder;
  1815. metadataNet.selectorPost = selectorReadFolderForced;
  1816. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1817. if (!autoUploadDirectory)
  1818. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1819. }
  1820. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1821. {
  1822. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1823. NSString *fileNamePlist;
  1824. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1825. if (![fileNameFolder length]) return;
  1826. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1827. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1828. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1829. // Create folder
  1830. metadataNet.action = actionCreateFolder;
  1831. metadataNet.fileName = fileNamePlist;
  1832. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1833. metadataNet.selector = selectorCreateFolder;
  1834. metadataNet.serverUrl = _serverUrl;
  1835. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1836. // upload plist file
  1837. metadataNet.action = actionUploadOnlyPlist;
  1838. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1839. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1840. metadataNet.selectorPost = selectorReadFolderForced;
  1841. metadataNet.serverUrl = _serverUrl;
  1842. metadataNet.session = k_upload_session_foreground;
  1843. metadataNet.taskStatus = k_taskStatusResume;
  1844. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1845. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1846. }
  1847. - (void)createFolderAutoUpload
  1848. {
  1849. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1850. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1851. }
  1852. #pragma --------------------------------------------------------------------------------------------
  1853. #pragma mark ===== Encrypted / Decrypted Folder =====
  1854. #pragma --------------------------------------------------------------------------------------------
  1855. - (void)encyptedDecryptedFolder
  1856. {
  1857. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1858. if (_metadata.cryptated) {
  1859. // DECRYPTED
  1860. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1861. //-------------------------- RENAME -------------------------------------------//
  1862. metadataNet.action = actionMoveFileOrFolder;
  1863. metadataNet.fileID = _metadata.fileID;
  1864. metadataNet.fileName = _metadata.fileNameData;
  1865. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1866. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1867. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1868. metadataNet.selector = selectorRename;
  1869. metadataNet.serverUrl = serverUrl;
  1870. metadataNet.serverUrlTo = serverUrl;
  1871. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1872. //-------------------------- DELETE -------------------------------------------//
  1873. metadataNet.action = actionDeleteFileDirectory;
  1874. metadataNet.fileID = _metadata.fileID;
  1875. metadataNet.fileName = _metadata.fileName;
  1876. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1877. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1878. metadataNet.selector = selectorDeletePlist;
  1879. metadataNet.selectorPost = selectorReadFolderForced;
  1880. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1881. } else {
  1882. // ENCRYPTED
  1883. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1884. // Create File Plist
  1885. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1886. //-------------------------- RENAME -------------------------------------------//
  1887. metadataNet.action = actionMoveFileOrFolder;
  1888. metadataNet.fileID = _metadata.fileID;
  1889. metadataNet.fileName = _metadata.fileName;
  1890. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1891. metadataNet.fileNameTo = fileNameCrypto;
  1892. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1893. metadataNet.selector = selectorRename;
  1894. metadataNet.serverUrl = serverUrl;
  1895. metadataNet.serverUrlTo = serverUrl;
  1896. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1897. //-------------------------- UPLOAD -------------------------------------------//
  1898. metadataNet.action = actionUploadOnlyPlist;
  1899. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1900. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1901. metadataNet.selectorPost = selectorReadFolderForced;
  1902. metadataNet.serverUrl = serverUrl;
  1903. metadataNet.session = k_upload_session_foreground;
  1904. metadataNet.taskStatus = k_taskStatusResume;
  1905. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1906. }
  1907. }
  1908. #pragma --------------------------------------------------------------------------------------------
  1909. #pragma mark ===== Encrypted/Decrypted File =====
  1910. #pragma --------------------------------------------------------------------------------------------
  1911. - (void)encryptedSelectedFiles
  1912. {
  1913. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1914. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1915. for (tableMetadata *metadata in selectedMetadatas) {
  1916. if (metadata.cryptated == NO && metadata.directory == NO)
  1917. [metadatas addObject:metadata];
  1918. }
  1919. if ([metadatas count] > 0) {
  1920. NSLog(@"[LOG] Start encrypted selected files ...");
  1921. for (tableMetadata* metadata in metadatas) {
  1922. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1923. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1924. }
  1925. }
  1926. [self tableViewSelect:NO];
  1927. }
  1928. - (void)decryptedSelectedFiles
  1929. {
  1930. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1931. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1932. for (tableMetadata *metadata in selectedMetadatas) {
  1933. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1934. [metadatas addObject:metadata];
  1935. }
  1936. if ([metadatas count] > 0) {
  1937. NSLog(@"[LOG] Start decrypted selected files ...");
  1938. for (tableMetadata* metadata in metadatas) {
  1939. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1940. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1941. }
  1942. }
  1943. [self tableViewSelect:NO];
  1944. }
  1945. - (void)cmdEncryptedDecryptedFile
  1946. {
  1947. NSString *selector;
  1948. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1949. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1950. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1951. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1952. }
  1953. - (void)encryptedFile:(tableMetadata *)metadata
  1954. {
  1955. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1956. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1957. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1958. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1959. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1960. dispatch_async(dispatch_get_main_queue(), ^{
  1961. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1962. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1963. });
  1964. } else {
  1965. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1966. }
  1967. }
  1968. - (void)decryptedFile:(tableMetadata *)metadata
  1969. {
  1970. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1971. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1972. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1973. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1974. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1975. dispatch_async(dispatch_get_main_queue(), ^{
  1976. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1977. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1978. });
  1979. } else {
  1980. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1981. }
  1982. }
  1983. #pragma --------------------------------------------------------------------------------------------
  1984. #pragma mark ===== Progress & Task Button =====
  1985. #pragma --------------------------------------------------------------------------------------------
  1986. - (void)triggerProgressTask:(NSNotification *)notification
  1987. {
  1988. NSDictionary *dict = notification.userInfo;
  1989. NSString *fileID = [dict valueForKey:@"fileID"];
  1990. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1991. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1992. float progress = [[dict valueForKey:@"progress"] floatValue];
  1993. // Check
  1994. if (!fileID)
  1995. return;
  1996. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1997. if (![serverUrl isEqualToString:_serverUrl])
  1998. return;
  1999. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  2000. if (indexPath) {
  2001. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  2002. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  2003. else cell.progressView.progressTintColor = [UIColor blackColor];
  2004. cell.progressView.hidden = NO;
  2005. [cell.progressView setProgress:progress];
  2006. }
  2007. if (progress == 0)
  2008. [self.navigationController cancelCCProgress];
  2009. else
  2010. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  2011. }
  2012. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  2013. {
  2014. UITouch * touch = [[event allTouches] anyObject];
  2015. CGPoint location = [touch locationInView:self.tableView];
  2016. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2017. if (indexPath) {
  2018. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2019. if (metadata)
  2020. [self reloadTaskButton:metadata];
  2021. }
  2022. }
  2023. - (void)reloadTaskButton:(tableMetadata *)metadata
  2024. {
  2025. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2026. __block NSURLSessionTask *findTask;
  2027. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2028. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2029. NSString *fileID = metadata.fileID;
  2030. // DOWNLOAD
  2031. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2032. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2033. for (NSURLSessionUploadTask *task in downloadTasks)
  2034. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2035. findTask = task;
  2036. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2037. [task cancel];
  2038. }
  2039. if (!findTask) {
  2040. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2041. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2042. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2043. }
  2044. }];
  2045. }
  2046. // UPLOAD
  2047. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2048. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2049. for (NSURLSessionUploadTask *task in uploadTasks)
  2050. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2051. findTask = task;
  2052. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2053. [task cancel];
  2054. }
  2055. if (!findTask) {
  2056. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2057. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2058. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2059. }
  2060. }];
  2061. }
  2062. }
  2063. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2064. {
  2065. UITouch * touch = [[event allTouches] anyObject];
  2066. CGPoint location = [touch locationInView:self.tableView];
  2067. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2068. if (indexPath) {
  2069. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2070. if (metadata)
  2071. [self cancelTaskButton:metadata reloadTable:YES];
  2072. }
  2073. }
  2074. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2075. {
  2076. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2077. __block NSURLSessionTask *findTask;
  2078. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2079. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2080. NSString *fileID = metadata.fileID;
  2081. // DOWNLOAD
  2082. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2083. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2084. for (NSURLSessionTask *task in downloadTasks)
  2085. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2086. findTask = task;
  2087. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2088. [task cancel];
  2089. }
  2090. if (!findTask) {
  2091. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2092. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2093. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2094. }
  2095. }];
  2096. }
  2097. // UPLOAD
  2098. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2099. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2100. for (NSURLSessionUploadTask *task in uploadTasks)
  2101. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2102. findTask = task;
  2103. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2104. [task cancel];
  2105. }
  2106. if (!findTask) {
  2107. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2108. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2109. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2110. }
  2111. }];
  2112. }
  2113. }
  2114. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2115. {
  2116. UITouch * touch = [[event allTouches] anyObject];
  2117. CGPoint location = [touch locationInView:self.tableView];
  2118. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2119. if (indexPath) {
  2120. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2121. if (metadata)
  2122. [self stopTaskButton:metadata];
  2123. }
  2124. }
  2125. - (void)stopTaskButton:(tableMetadata *)metadata
  2126. {
  2127. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2128. __block NSURLSessionTask *findTask;
  2129. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2130. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2131. NSString *fileID = metadata.fileID;
  2132. // UPLOAD
  2133. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2134. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2135. for (NSURLSessionUploadTask *task in uploadTasks)
  2136. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2137. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2138. findTask = task;
  2139. [task cancel];
  2140. }
  2141. if (!findTask) {
  2142. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2143. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2144. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2145. }
  2146. }];
  2147. }
  2148. }
  2149. #pragma --------------------------------------------------------------------------------------------
  2150. #pragma mark ===== Shared =====
  2151. #pragma --------------------------------------------------------------------------------------------
  2152. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2153. {
  2154. [_hud hideHud];
  2155. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2156. // change account ?
  2157. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2158. if([record.account isEqualToString:metadataNet.account] == NO)
  2159. return;
  2160. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2161. if (result) {
  2162. appDelegate.sharesLink = result[0];
  2163. appDelegate.sharesUserAndGroup = result[1];
  2164. }
  2165. // Notify Shares View
  2166. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2167. if (openWindow) {
  2168. if (_shareOC) {
  2169. [_shareOC reloadData];
  2170. } else {
  2171. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2172. // Apriamo la view
  2173. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2174. _shareOC.delegate = self;
  2175. _shareOC.metadata = metadata;
  2176. _shareOC.serverUrl = metadataNet.serverUrl;
  2177. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2178. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2179. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2180. [self presentViewController:_shareOC animated:YES completion:nil];
  2181. }
  2182. }
  2183. [self tableViewReloadData];
  2184. }
  2185. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2186. {
  2187. [_hud hideHud];
  2188. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2189. if (_shareOC)
  2190. [_shareOC reloadData];
  2191. [self tableViewReloadData];
  2192. if (errorCode == 401)
  2193. [self changePasswordAccount];
  2194. }
  2195. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2196. {
  2197. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2198. metadataNet.action = actionShare;
  2199. metadataNet.fileID = metadata.fileID;
  2200. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2201. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2202. metadataNet.password = password;
  2203. metadataNet.selector = selectorShare;
  2204. metadataNet.serverUrl = serverUrl;
  2205. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2206. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2207. }
  2208. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2209. {
  2210. [_hud hideHud];
  2211. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2212. // rimuoviamo la condivisione da db
  2213. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2214. if (result) {
  2215. appDelegate.sharesLink = result[0];
  2216. appDelegate.sharesUserAndGroup = result[1];
  2217. }
  2218. if (_shareOC)
  2219. [_shareOC reloadData];
  2220. [self tableViewReloadData];
  2221. }
  2222. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2223. {
  2224. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2225. metadataNet.action = actionUnShare;
  2226. metadataNet.fileID = metadata.fileID;
  2227. metadataNet.fileName = metadata.fileName;
  2228. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2229. metadataNet.selector = selectorUnshare;
  2230. metadataNet.serverUrl = serverUrl;
  2231. metadataNet.share = share;
  2232. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2233. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2234. }
  2235. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2236. {
  2237. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2238. metadataNet.action = actionUpdateShare;
  2239. metadataNet.fileID = metadata.fileID;
  2240. metadataNet.expirationTime = expirationTime;
  2241. metadataNet.password = password;
  2242. metadataNet.selector = selectorUpdateShare;
  2243. metadataNet.serverUrl = serverUrl;
  2244. metadataNet.share = share;
  2245. metadataNet.sharePermission = permission;
  2246. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2247. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2248. }
  2249. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2250. {
  2251. [_hud hideHud];
  2252. if (_shareOC)
  2253. [_shareOC reloadUserAndGroup:items];
  2254. }
  2255. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2256. {
  2257. [_hud hideHud];
  2258. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2259. }
  2260. - (void)getUserAndGroup:(NSString *)find
  2261. {
  2262. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2263. metadataNet.action = actionGetUserAndGroup;
  2264. metadataNet.options = find;
  2265. metadataNet.selector = selectorGetUserAndGroup;
  2266. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2267. [_hud visibleIndeterminateHud];
  2268. }
  2269. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2270. {
  2271. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2272. metadataNet.action = actionShareWith;
  2273. metadataNet.fileID = metadata.fileID;
  2274. metadataNet.directoryID = directoryID;
  2275. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2276. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2277. metadataNet.serverUrl = serverUrl;
  2278. metadataNet.selector = selectorShare;
  2279. metadataNet.share = user;
  2280. metadataNet.shareeType = shareeType;
  2281. metadataNet.sharePermission = permission;
  2282. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2283. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2284. }
  2285. - (void)openWindowShare:(tableMetadata *)metadata
  2286. {
  2287. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2288. metadataNet.action = actionReadShareServer;
  2289. metadataNet.fileID = metadata.fileID;
  2290. metadataNet.fileName = metadata.fileName;
  2291. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2292. metadataNet.selector = selectorOpenWindowShare;
  2293. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2294. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2295. [_hud visibleIndeterminateHud];
  2296. }
  2297. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2298. {
  2299. CGPoint location = [tapGesture locationInView:self.tableView];
  2300. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2301. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2302. if (metadata)
  2303. [self openWindowShare:metadata];
  2304. }
  2305. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2306. {
  2307. CGPoint location = [tapGesture locationInView:self.tableView];
  2308. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2309. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2310. if (metadata) {
  2311. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2312. vc.metadata = metadata;
  2313. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2314. [self presentViewController:vc animated:YES completion:nil];
  2315. }
  2316. }
  2317. #pragma --------------------------------------------------------------------------------------------
  2318. #pragma mark ===== Favorite =====
  2319. #pragma --------------------------------------------------------------------------------------------
  2320. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2321. {
  2322. _dateReadDataSource = nil;
  2323. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2324. if (_isSearchMode)
  2325. [self readFolder:metadataNet.serverUrl];
  2326. else
  2327. [self reloadDatasource:metadataNet.serverUrl];
  2328. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2329. if (metadata.directory && metadata.favorite) {
  2330. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2331. [app.activeFavorites addFavoriteFolder:dir];
  2332. }
  2333. }
  2334. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2335. {
  2336. }
  2337. - (void)addFavorite:(tableMetadata *)metadata
  2338. {
  2339. if (metadata.directory) {
  2340. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2341. } else {
  2342. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2343. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2344. }
  2345. }
  2346. - (void)removeFavorite:(tableMetadata *)metadata
  2347. {
  2348. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2349. }
  2350. #pragma --------------------------------------------------------------------------------------------
  2351. #pragma mark ===== Local =====
  2352. #pragma --------------------------------------------------------------------------------------------
  2353. - (void)addLocal:(tableMetadata *)metadata
  2354. {
  2355. if (metadata.errorPasscode || !metadata.uuid) return;
  2356. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2357. if ([metadata.type isEqualToString: k_metadataType_file])
  2358. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2359. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2360. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2361. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2362. }
  2363. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2364. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2365. }
  2366. #pragma --------------------------------------------------------------------------------------------
  2367. #pragma mark ===== Open in... =====
  2368. #pragma --------------------------------------------------------------------------------------------
  2369. - (void)openIn:(tableMetadata *)metadata
  2370. {
  2371. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2372. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2373. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2374. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2375. }
  2376. #pragma --------------------------------------------------------------------------------------------
  2377. #pragma mark ===== Remove Local File =====
  2378. #pragma --------------------------------------------------------------------------------------------
  2379. - (void)removeLocalFile:(tableMetadata *)metadata
  2380. {
  2381. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2382. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2383. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2384. [self reloadDatasource:serverUrl];
  2385. }
  2386. #pragma --------------------------------------------------------------------------------------------
  2387. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2388. #pragma --------------------------------------------------------------------------------------------
  2389. - (void)orderTable:(NSString *)order
  2390. {
  2391. [CCUtility setOrderSettings:order];
  2392. // Clear data-read of DataSource
  2393. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2394. }
  2395. - (void)ascendingTable:(BOOL)ascending
  2396. {
  2397. [CCUtility setAscendingSettings:ascending];
  2398. // Clear data-read of DataSource
  2399. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2400. }
  2401. - (void)directoryOnTop:(BOOL)directoryOnTop
  2402. {
  2403. [CCUtility setDirectoryOnTop:directoryOnTop];
  2404. // Clear data-read of DataSource
  2405. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2406. }
  2407. - (void)tableGroupBy:(NSString *)groupBy
  2408. {
  2409. [CCUtility setGroupBySettings:groupBy];
  2410. // Clear data-read of DataSource
  2411. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2412. }
  2413. #pragma --------------------------------------------------------------------------------------------
  2414. #pragma mark ==== Menu LOGO ====
  2415. #pragma --------------------------------------------------------------------------------------------
  2416. - (void)menuLogo
  2417. {
  2418. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2419. return;
  2420. // Brand
  2421. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2422. return;
  2423. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutoUploadWithSession:nil] > 0) {
  2424. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2425. return;
  2426. }
  2427. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2428. NSMutableArray *menuArray = [NSMutableArray new];
  2429. for (NSString *account in listAccount) {
  2430. if ([account isEqualToString:app.activeAccount]) continue;
  2431. CCMenuItem *item = [[CCMenuItem alloc] init];
  2432. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2433. item.argument = account;
  2434. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2435. item.target = self;
  2436. item.action = @selector(changeDefaultAccount:);
  2437. [menuArray addObject:item];
  2438. }
  2439. if ([menuArray count] == 0)
  2440. return;
  2441. OptionalConfiguration options;
  2442. Color textColor, backgroundColor;
  2443. textColor.R = 0;
  2444. textColor.G = 0;
  2445. textColor.B = 0;
  2446. backgroundColor.R = 1;
  2447. backgroundColor.G = 1;
  2448. backgroundColor.B = 1;
  2449. NSInteger originY = 60;
  2450. options.arrowSize = 9;
  2451. options.marginXSpacing = 7;
  2452. options.marginYSpacing = 10;
  2453. options.intervalSpacing = 20;
  2454. options.menuCornerRadius = 6.5;
  2455. options.maskToBackground = NO;
  2456. options.shadowOfMenu = YES;
  2457. options.hasSeperatorLine = YES;
  2458. options.seperatorLineHasInsets = YES;
  2459. options.textColor = textColor;
  2460. options.menuBackgroundColor = backgroundColor;
  2461. CGRect rect = self.view.frame;
  2462. rect.origin.y = rect.origin.y + originY;
  2463. rect.size.height = rect.size.height - originY;
  2464. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2465. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2466. }
  2467. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2468. {
  2469. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2470. // STOP, erase all in queue networking
  2471. [app cancelAllOperations];
  2472. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2473. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2474. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2475. if (tableAccount)
  2476. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2477. // go to home sweet home
  2478. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2479. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2480. });
  2481. }
  2482. #pragma --------------------------------------------------------------------------------------------
  2483. #pragma mark ==== ReMenu ====
  2484. #pragma --------------------------------------------------------------------------------------------
  2485. - (void)createReMenuBackgroundView:(REMenu *)menu
  2486. {
  2487. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2488. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2489. [UIView animateWithDuration:0.2 animations:^{
  2490. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2491. if (height < self.tabBarController.tabBar.frame.size.height)
  2492. height = self.tabBarController.tabBar.frame.size.height;
  2493. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2494. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2495. }];
  2496. }
  2497. - (void)createReMainMenu
  2498. {
  2499. NSString *ordinamento;
  2500. NSString *groupBy = _directoryGroupBy;
  2501. __block NSString *nuovoOrdinamento;
  2502. NSString *titoloNuovo, *titoloAttuale;
  2503. BOOL ascendente;
  2504. __block BOOL nuovoAscendente;
  2505. UIImage *image;
  2506. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2507. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2508. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2509. [self tableViewSelect:YES];
  2510. }
  2511. }];
  2512. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2513. ordinamento = _directoryOrder;
  2514. if ([ordinamento isEqualToString:@"fileName"]) {
  2515. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2516. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2517. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2518. nuovoOrdinamento = @"date";
  2519. }
  2520. if ([ordinamento isEqualToString:@"date"]) {
  2521. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2522. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2523. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2524. nuovoOrdinamento = @"fileName";
  2525. }
  2526. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2527. [self orderTable:nuovoOrdinamento];
  2528. }];
  2529. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2530. ascendente = [CCUtility getAscendingSettings];
  2531. if (ascendente) {
  2532. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2533. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2534. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2535. nuovoAscendente = false;
  2536. }
  2537. if (!ascendente) {
  2538. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2539. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2540. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2541. nuovoAscendente = true;
  2542. }
  2543. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2544. [self ascendingTable:nuovoAscendente];
  2545. }];
  2546. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2547. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2548. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2549. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2550. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2551. else [self tableGroupBy:@"alphabetic"];
  2552. }];
  2553. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2554. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2555. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2556. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2557. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2558. else [self tableGroupBy:@"typefile"];
  2559. }];
  2560. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2561. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2562. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2563. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2564. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2565. else [self tableGroupBy:@"date"];
  2566. }];
  2567. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2568. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2569. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2570. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2571. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2572. else [self directoryOnTop:YES];
  2573. }];
  2574. // REMENU --------------------------------------------------------------------------------------------------------------
  2575. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2576. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2577. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2578. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2579. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2580. app.reMainMenu.separatorHeight = 0.5;
  2581. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2582. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2583. app.reMainMenu.textColor = [UIColor blackColor];
  2584. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2585. app.reMainMenu.textShadowColor = nil;
  2586. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2587. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2588. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2589. app.reMainMenu.highlightedSeparatorColor = nil;
  2590. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2591. app.reMainMenu.highlightedTextShadowColor = nil;
  2592. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2593. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2594. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2595. app.reMainMenu.subtitleTextShadowColor = nil;
  2596. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2597. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2598. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2599. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2600. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2601. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2602. app.reMainMenu.borderWidth = 0.3;
  2603. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2604. app.reMainMenu.animationDuration = 0.2;
  2605. app.reMainMenu.closeAnimationDuration = 0.2;
  2606. app.reMainMenu.bounce = NO;
  2607. [app.reMainMenu setClosePreparationBlock:^{
  2608. // Backgroun reMenu (Gesture)
  2609. [_reMenuBackgroundView removeFromSuperview];
  2610. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2611. }];
  2612. }
  2613. - (void)toggleReMainMenu
  2614. {
  2615. if (app.reMainMenu.isOpen) {
  2616. [app.reMainMenu close];
  2617. } else {
  2618. [self createReMainMenu];
  2619. [app.reMainMenu showFromNavigationController:self.navigationController];
  2620. // Backgroun reMenu & (Gesture)
  2621. [self createReMenuBackgroundView:app.reMainMenu];
  2622. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2623. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2624. }
  2625. }
  2626. - (void)createReSelectMenu
  2627. {
  2628. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2629. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2630. [self deleteFile];
  2631. }];
  2632. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2633. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2634. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2635. }];
  2636. if (app.isCryptoCloudMode) {
  2637. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2638. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2639. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2640. }];
  2641. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2642. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2643. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2644. }];
  2645. }
  2646. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2647. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2648. [self downloadSelectedFilesFolders];
  2649. }];
  2650. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2651. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2652. [self saveSelectedFiles];
  2653. }];
  2654. // REMENU --------------------------------------------------------------------------------------------------------------
  2655. if (app.isCryptoCloudMode) {
  2656. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2657. } else {
  2658. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2659. }
  2660. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2661. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2662. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2663. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2664. app.reSelectMenu.separatorHeight = 0.5;
  2665. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2666. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2667. app.reSelectMenu.textColor = [UIColor blackColor];
  2668. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2669. app.reSelectMenu.textShadowColor = nil;
  2670. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2671. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2672. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2673. app.reSelectMenu.highlightedSeparatorColor = nil;
  2674. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2675. app.reSelectMenu.highlightedTextShadowColor = nil;
  2676. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2677. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2678. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2679. app.reSelectMenu.subtitleTextShadowColor = nil;
  2680. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2681. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2682. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2683. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2684. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2685. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2686. app.reSelectMenu.borderWidth = 0.3;
  2687. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2688. app.reSelectMenu.closeAnimationDuration = 0.2;
  2689. app.reSelectMenu.animationDuration = 0.2;
  2690. app.reSelectMenu.bounce = NO;
  2691. [app.reSelectMenu setClosePreparationBlock:^{
  2692. // Backgroun reMenu (Gesture)
  2693. [_reMenuBackgroundView removeFromSuperview];
  2694. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2695. }];
  2696. }
  2697. - (void)toggleReSelectMenu
  2698. {
  2699. if (app.reSelectMenu.isOpen) {
  2700. [app.reSelectMenu close];
  2701. } else {
  2702. [self createReSelectMenu];
  2703. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2704. // Backgroun reMenu & (Gesture)
  2705. [self createReMenuBackgroundView:app.reSelectMenu];
  2706. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2707. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2708. }
  2709. }
  2710. #pragma --------------------------------------------------------------------------------------------
  2711. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2712. #pragma --------------------------------------------------------------------------------------------
  2713. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2714. {
  2715. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2716. UITableView *tableView = (UITableView*)self.view;
  2717. CGPoint touchPoint = [recognizer locationInView:self.view];
  2718. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2719. if (indexPath)
  2720. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2721. else
  2722. _metadata = nil;
  2723. [self becomeFirstResponder];
  2724. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2725. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2726. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2727. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2728. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2729. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2730. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2731. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2732. if (app.isCryptoCloudMode)
  2733. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2734. else
  2735. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2736. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2737. [menuController setMenuVisible:YES animated:YES];
  2738. }
  2739. }
  2740. - (BOOL)canBecomeFirstResponder
  2741. {
  2742. return YES;
  2743. }
  2744. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2745. {
  2746. // For copy file, copy files, Open in ... :
  2747. //
  2748. // NO Directory
  2749. // NO Error Passcode
  2750. // NO In Session mode (download/upload)
  2751. // NO Template
  2752. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2753. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2754. // NO Cryptated with Title lenght = 0
  2755. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2756. return YES;
  2757. }
  2758. return NO;
  2759. }
  2760. if (@selector(copyFiles:) == action) {
  2761. if (_isSelectedMode) {
  2762. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2763. for (tableMetadata *metadata in selectedMetadatas) {
  2764. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2765. // NO Cryptated with Title lenght = 0
  2766. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2767. return YES;
  2768. }
  2769. }
  2770. }
  2771. return NO;
  2772. }
  2773. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2774. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2775. NSArray *items = [pasteboard items];
  2776. if ([items count] == 1) {
  2777. // Value : (NSData) fileID
  2778. NSDictionary *dic = [items objectAtIndex:0];
  2779. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2780. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2781. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2782. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2783. if (directoryUser) {
  2784. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2785. return YES;
  2786. }
  2787. return NO;
  2788. } else return NO;
  2789. }
  2790. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2791. BOOL isValid = NO;
  2792. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2793. NSArray *items = [pasteboard items];
  2794. if ([items count] <= 1) return NO;
  2795. for (NSDictionary *dic in items) {
  2796. // Value : (NSData) fileID
  2797. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2798. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2799. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2800. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2801. if (directoryUser) {
  2802. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2803. isValid = YES;
  2804. }
  2805. }
  2806. return isValid;
  2807. }
  2808. return NO;
  2809. }
  2810. /************************************ COPY ************************************/
  2811. - (void)copyFile:(id)sender
  2812. {
  2813. // Remove all item
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. pasteboard.items = [[NSArray alloc] init];
  2816. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2817. [self copyFileToPasteboard:_metadata];
  2818. } else {
  2819. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2820. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2821. }
  2822. }
  2823. - (void)copyFiles:(id)sender
  2824. {
  2825. // Remove all item
  2826. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2827. pasteboard.items = [[NSArray alloc] init];
  2828. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2829. for (tableMetadata *metadata in selectedMetadatas) {
  2830. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2831. [self copyFileToPasteboard:metadata];
  2832. } else {
  2833. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2834. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2835. }
  2836. }
  2837. [self tableViewSelect:NO];
  2838. }
  2839. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2840. {
  2841. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2842. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2843. // Value : (NSData) fileID
  2844. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2845. [items addObject:item];
  2846. [pasteboard setItems:items];
  2847. }
  2848. /************************************ OPEN IN ... ************************************/
  2849. - (void)openinFile:(id)sender
  2850. {
  2851. [self openIn:_metadata];
  2852. }
  2853. /************************************ PASTE ************************************/
  2854. - (void)pasteFile:(id)sender
  2855. {
  2856. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2857. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2858. }
  2859. - (void)pasteFileEncrypted:(id)sender
  2860. {
  2861. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2862. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2863. }
  2864. - (void)pasteFiles:(id)sender
  2865. {
  2866. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2867. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2868. }
  2869. - (void)pasteFilesEncrypted:(id)sender
  2870. {
  2871. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2872. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2873. }
  2874. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2875. {
  2876. for (NSDictionary *dic in items) {
  2877. // Value : (NSData) fileID
  2878. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2879. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2880. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2881. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2882. if (!metadata || !account) return;
  2883. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2884. if (directoryUser) {
  2885. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2886. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2887. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2888. }
  2889. }
  2890. }
  2891. }
  2892. #pragma --------------------------------------------------------------------------------------------
  2893. #pragma mark ===== Lock Passcode =====
  2894. #pragma --------------------------------------------------------------------------------------------
  2895. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2896. {
  2897. return _failedAttempts;
  2898. }
  2899. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2900. {
  2901. return _lockUntilDate;
  2902. }
  2903. - (void)passcodeViewCloseButtonPressed:(id)sender
  2904. {
  2905. [self dismissViewControllerAnimated:YES completion:nil];
  2906. }
  2907. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2908. {
  2909. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2910. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2911. _lockUntilDate = nil;
  2912. _failedAttempts = 0;
  2913. aResultHandler(YES);
  2914. } else aResultHandler(NO);
  2915. } else aResultHandler(YES);
  2916. }
  2917. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2918. {
  2919. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2920. switch (aViewController.type) {
  2921. case BKPasscodeViewControllerCheckPasscodeType: {
  2922. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2923. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2924. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2925. // scriviamo il passcode
  2926. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2927. [self readFolder:_serverUrl];
  2928. } else {
  2929. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2930. [alertView show];
  2931. }
  2932. }
  2933. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2934. // possiamo procedere alla prossima directory
  2935. [self performSegueDirectoryWithControlPasscode:false];
  2936. // avviamo la sessione Passcode Lock con now
  2937. app.sessionePasscodeLock = [NSDate date];
  2938. }
  2939. // disattivazione lock cartella
  2940. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2941. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2942. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2943. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2944. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2945. }
  2946. [self tableViewReloadData];
  2947. }
  2948. }
  2949. break;
  2950. default:
  2951. break;
  2952. }
  2953. }
  2954. - (void)comandoLockPassword
  2955. {
  2956. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2957. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2958. // se non è abilitato il Lock Passcode esci
  2959. if ([[CCUtility getBlockCode] length] == 0) {
  2960. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2961. [alertView show];
  2962. return;
  2963. }
  2964. // se è richiesta la disattivazione si chiede la password
  2965. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2966. if (directory.lock) {
  2967. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2968. viewController.delegate = self;
  2969. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2970. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2971. viewController.inputViewTitlePassword = YES;
  2972. if ([CCUtility getSimplyBlockCode]) {
  2973. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2974. viewController.passcodeInputView.maximumLength = 6;
  2975. } else {
  2976. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2977. viewController.passcodeInputView.maximumLength = 64;
  2978. }
  2979. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2980. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2981. viewController.touchIDManager = touchIDManager;
  2982. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2983. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2984. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2985. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2986. [self presentViewController:navigationController animated:YES completion:nil];
  2987. return;
  2988. }
  2989. // ---------------- ACTIVATE PASSWORD
  2990. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2991. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2992. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2993. } else {
  2994. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2995. }
  2996. }
  2997. #pragma mark -
  2998. #pragma --------------------------------------------------------------------------------------------
  2999. #pragma mark ===== Swipe Tablet -> menu =====
  3000. #pragma --------------------------------------------------------------------------------------------
  3001. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  3002. {
  3003. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3004. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3005. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3006. return NO;
  3007. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0)
  3008. return NO;
  3009. return YES;
  3010. }
  3011. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  3012. {
  3013. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3014. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3015. if (direction == MGSwipeDirectionRightToLeft) {
  3016. // Delete
  3017. if (index == 0)
  3018. [self swipeDelete:indexPath];
  3019. // More
  3020. if (index == 1)
  3021. [self swipeMore:indexPath];
  3022. //dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  3023. //});
  3024. }
  3025. if (direction == MGSwipeDirectionLeftToRight) {
  3026. if (_metadata.favorite)
  3027. [self removeFavorite:_metadata];
  3028. else
  3029. [self addFavorite:_metadata];
  3030. }
  3031. return YES;
  3032. }
  3033. - (void)swipeDelete:(NSIndexPath *)indexPath
  3034. {
  3035. // Directory locked ?
  3036. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3037. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3038. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  3039. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3040. return;
  3041. }
  3042. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3043. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  3044. [self performSelector:@selector(deleteFile) withObject:nil];
  3045. }]];
  3046. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3047. [alertController dismissViewControllerAnimated:YES completion:nil];
  3048. }]];
  3049. alertController.popoverPresentationController.sourceView = self.view;
  3050. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3051. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3052. [alertController.view layoutIfNeeded];
  3053. [self presentViewController:alertController animated:YES completion:nil];
  3054. }
  3055. - (void)swipeMore:(NSIndexPath *)indexPath
  3056. {
  3057. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3058. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  3059. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3060. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3061. if (_metadata.favorite) {
  3062. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3063. } else {
  3064. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3065. }
  3066. if (_metadata.directory) {
  3067. // calcolo lockServerUrl
  3068. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3069. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3070. if (directory.lock)
  3071. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3072. else
  3073. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3074. }
  3075. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  3076. // ******************************************* AHKActionSheet *******************************************
  3077. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3078. actionSheet.animationDuration = 0.2;
  3079. actionSheet.blurRadius = 0.0f;
  3080. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3081. actionSheet.buttonHeight = 50.0;
  3082. actionSheet.cancelButtonHeight = 50.0f;
  3083. actionSheet.separatorHeight = 5.0f;
  3084. actionSheet.automaticallyTintButtonImages = @(NO);
  3085. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3086. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3087. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3088. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3089. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3090. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3091. // ******************************************* DIRECTORY *******************************************
  3092. if (_metadata.directory) {
  3093. BOOL lockDirectory = NO;
  3094. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3095. // Directory bloccata ?
  3096. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3097. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3098. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3099. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3100. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3101. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3102. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3103. height: 50.0
  3104. type: AHKActionSheetButtonTypeDisabled
  3105. handler: nil
  3106. ];
  3107. /*
  3108. if (!lockDirectory && !_metadata.cryptated) {
  3109. [actionSheet addButtonWithTitle:titleFavorite
  3110. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3111. backgroundColor:[UIColor whiteColor]
  3112. height: 50.0
  3113. type:AHKActionSheetButtonTypeDefault
  3114. handler:^(AHKActionSheet *as) {
  3115. // close swipe
  3116. [self setEditing:NO animated:YES];
  3117. if (_metadata.favorite)
  3118. [self removeFavorite:_metadata];
  3119. else
  3120. [self addFavorite:_metadata];
  3121. }];
  3122. }
  3123. */
  3124. if (_metadata.cryptated == NO && !lockDirectory) {
  3125. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3126. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3127. backgroundColor:[UIColor whiteColor]
  3128. height: 50.0
  3129. type:AHKActionSheetButtonTypeDefault
  3130. handler:^(AHKActionSheet *as) {
  3131. // close swipe
  3132. [self setEditing:NO animated:YES];
  3133. [self openWindowShare:_metadata];
  3134. }];
  3135. }
  3136. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3137. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3138. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3139. backgroundColor:[UIColor whiteColor]
  3140. height: 50.0
  3141. type:AHKActionSheetButtonTypeDefault
  3142. handler:^(AHKActionSheet *as) {
  3143. // close swipe
  3144. [self setEditing:NO animated:YES];
  3145. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3146. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3147. textField.text = _metadata.fileNamePrint;
  3148. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3149. //textField.delegate = self;
  3150. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3151. }];
  3152. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3153. NSLog(@"Cancel action");
  3154. }];
  3155. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3156. UITextField *fileName = alertController.textFields.firstObject;
  3157. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3158. }];
  3159. okAction.enabled = NO;
  3160. [alertController addAction:cancelAction];
  3161. [alertController addAction:okAction];
  3162. [self presentViewController:alertController animated:YES completion:nil];
  3163. }];
  3164. }
  3165. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3166. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3167. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3168. backgroundColor:[UIColor whiteColor]
  3169. height: 50.0
  3170. type:AHKActionSheetButtonTypeDefault
  3171. handler:^(AHKActionSheet *as) {
  3172. // close swipe
  3173. [self setEditing:NO animated:YES];
  3174. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3175. }];
  3176. }
  3177. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3178. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3179. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3180. backgroundColor:[UIColor whiteColor]
  3181. height: 50.0
  3182. type:AHKActionSheetButtonTypeDefault
  3183. handler:^(AHKActionSheet *as) {
  3184. // close swipe
  3185. [self setEditing:NO animated:YES];
  3186. // Settings new folder Automatatic upload
  3187. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3188. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3189. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3190. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3191. if (app.activeAccount.length > 0 && app.activePhotos)
  3192. [app.activePhotos reloadDatasourceForced];
  3193. [self readFolder:serverUrl];
  3194. NSLog(@"[LOG] Update Folder Photo");
  3195. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3196. if ([autoUploadPath length] > 0)
  3197. [[CCSynchronize sharedSynchronize] synchronizedFolder:autoUploadPath selector:selectorReadFolder];
  3198. }];
  3199. }
  3200. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3201. [actionSheet addButtonWithTitle:titoloLock
  3202. image:[UIImage imageNamed:@"actionSheetLock"]
  3203. backgroundColor:[UIColor whiteColor]
  3204. height: 50.0
  3205. type:AHKActionSheetButtonTypeEncrypted
  3206. handler:^(AHKActionSheet *as) {
  3207. // close swipe
  3208. [self setEditing:NO animated:YES];
  3209. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3210. }];
  3211. }
  3212. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3213. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3214. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3215. backgroundColor:[UIColor whiteColor]
  3216. height: 50.0
  3217. type:AHKActionSheetButtonTypeEncrypted
  3218. handler:^(AHKActionSheet *as) {
  3219. // close swipe
  3220. [self setEditing:NO animated:YES];
  3221. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3222. }];
  3223. }
  3224. [actionSheet show];
  3225. }
  3226. // ******************************************* FILE *******************************************
  3227. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3228. UIImage *iconHeader;
  3229. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3230. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3231. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3232. else
  3233. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3234. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3235. image: iconHeader
  3236. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3237. height: 50.0
  3238. type: AHKActionSheetButtonTypeDisabled
  3239. handler: nil
  3240. ];
  3241. /*
  3242. if (!_metadata.cryptated) {
  3243. [actionSheet addButtonWithTitle:titleFavorite
  3244. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3245. backgroundColor:[UIColor whiteColor]
  3246. height: 50.0
  3247. type:AHKActionSheetButtonTypeDefault
  3248. handler:^(AHKActionSheet *as) {
  3249. // close swipe
  3250. [self setEditing:NO animated:YES];
  3251. if (_metadata.favorite)
  3252. [self removeFavorite:_metadata];
  3253. else
  3254. [self addFavorite:_metadata];
  3255. }];
  3256. }
  3257. */
  3258. if (_metadata.cryptated == NO) {
  3259. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3260. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3261. backgroundColor:[UIColor whiteColor]
  3262. height: 50.0
  3263. type:AHKActionSheetButtonTypeDefault
  3264. handler:^(AHKActionSheet *as) {
  3265. // close swipe
  3266. [self setEditing:NO animated:YES];
  3267. [self openWindowShare:_metadata];
  3268. }];
  3269. }
  3270. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3271. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3272. backgroundColor:[UIColor whiteColor]
  3273. height: 50.0
  3274. type:AHKActionSheetButtonTypeDefault
  3275. handler:^(AHKActionSheet *as) {
  3276. // close swipe
  3277. [self setEditing:NO animated:YES];
  3278. [self performSelector:@selector(openIn:) withObject:_metadata];
  3279. }];
  3280. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3281. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3282. backgroundColor:[UIColor whiteColor]
  3283. height: 50.0
  3284. type:AHKActionSheetButtonTypeDefault
  3285. handler:^(AHKActionSheet *as) {
  3286. // close swipe
  3287. [self setEditing:NO animated:YES];
  3288. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3289. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3290. //textField.placeholder = _metadata.fileNamePrint;
  3291. textField.text = _metadata.fileNamePrint;
  3292. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3293. }];
  3294. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3295. NSLog(@"Cancel action");
  3296. }];
  3297. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3298. UITextField *fileName = alertController.textFields.firstObject;
  3299. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3300. }];
  3301. okAction.enabled = NO;
  3302. [alertController addAction:cancelAction];
  3303. [alertController addAction:okAction];
  3304. [self presentViewController:alertController animated:YES completion:nil];
  3305. }];
  3306. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3307. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3308. backgroundColor:[UIColor whiteColor]
  3309. height: 50.0
  3310. type:AHKActionSheetButtonTypeDefault
  3311. handler:^(AHKActionSheet *as) {
  3312. // close swipe
  3313. [self setEditing:NO animated:YES];
  3314. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3315. }];
  3316. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3317. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3318. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3319. backgroundColor:[UIColor whiteColor]
  3320. height: 50.0
  3321. type:AHKActionSheetButtonTypeDefault
  3322. handler:^(AHKActionSheet *as) {
  3323. // close swipe
  3324. [self setEditing:NO animated:YES];
  3325. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3326. }];
  3327. }
  3328. if (app.isCryptoCloudMode) {
  3329. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3330. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3331. backgroundColor:[UIColor whiteColor]
  3332. height: 50.0
  3333. type:AHKActionSheetButtonTypeEncrypted
  3334. handler:^(AHKActionSheet *as) {
  3335. // close swipe
  3336. [self setEditing:NO animated:YES];
  3337. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3338. }];
  3339. }
  3340. [actionSheet show];
  3341. }
  3342. // ******************************************* TEMPLATE *******************************************
  3343. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3344. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3345. image: [UIImage imageNamed:_metadata.iconName]
  3346. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3347. height: 50.0
  3348. type: AHKActionSheetButtonTypeDisabled
  3349. handler: nil
  3350. ];
  3351. if ([_metadata.model isEqualToString:@"note"]) {
  3352. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3353. image:[UIImage imageNamed:@"actionSheetRename"]
  3354. backgroundColor:[UIColor whiteColor]
  3355. height: 50.0
  3356. type:AHKActionSheetButtonTypeDefault
  3357. handler:^(AHKActionSheet *as) {
  3358. // close swipe
  3359. [self setEditing:NO animated:YES];
  3360. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3361. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3362. textField.placeholder = _metadata.fileNamePrint;
  3363. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3364. }];
  3365. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3366. NSLog(@"Cancel action");
  3367. }];
  3368. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3369. UITextField *fileName = alertController.textFields.firstObject;
  3370. [self performSelectorOnMainThread:@selector(renameNote:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3371. }];
  3372. okAction.enabled = NO;
  3373. [alertController addAction:cancelAction];
  3374. [alertController addAction:okAction];
  3375. [self presentViewController:alertController animated:YES completion:nil];
  3376. }];
  3377. }
  3378. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3379. image:[UIImage imageNamed:@"actionSheetMove"]
  3380. backgroundColor:[UIColor whiteColor]
  3381. height: 50.0
  3382. type:AHKActionSheetButtonTypeDefault
  3383. handler:^(AHKActionSheet *as) {
  3384. // close swipe
  3385. [self setEditing:NO animated:YES];
  3386. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3387. }];
  3388. [actionSheet show];
  3389. }
  3390. }
  3391. /*
  3392. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3393. {
  3394. //Nothing gets called here if you invoke `tableView:editActionsForRowAtIndexPath:` according to Apple docs so just leave this method blank
  3395. }
  3396. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3397. {
  3398. // the cells you would like the actions to appear needs to be editable
  3399. }
  3400. - (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
  3401. {
  3402. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3403. // ---- DELETE ----
  3404. UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:NSLocalizedString(@"_delete_", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  3405. }];
  3406. // ---- MORE ----
  3407. UITableViewRowAction *more = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:NSLocalizedString(@"_more_", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  3408. }];
  3409. more.backgroundColor = [UIColor lightGrayColor];
  3410. return @[delete, more];
  3411. }
  3412. */
  3413. #pragma --------------------------------------------------------------------------------------------
  3414. #pragma mark - ==== Datasource ====
  3415. #pragma --------------------------------------------------------------------------------------------
  3416. - (void)clearDateReadDataSource:(NSNotification *)notification
  3417. {
  3418. _dateReadDataSource = Nil;
  3419. [self reloadDatasource];
  3420. }
  3421. - (void)reloadDatasource
  3422. {
  3423. [self reloadDatasource:_serverUrl];
  3424. }
  3425. - (void)reloadDatasource:(NSString *)serverUrl
  3426. {
  3427. // test
  3428. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3429. return;
  3430. // Search Mode
  3431. if(_isSearchMode) {
  3432. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3433. [self tableViewReloadData];
  3434. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3435. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3436. _noFilesSearchDescription = @"";
  3437. }
  3438. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3439. _noFilesSearchTitle = @"";
  3440. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3441. }
  3442. [self.tableView reloadEmptyDataSet];
  3443. return;
  3444. }
  3445. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3446. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3447. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3448. if (main) {
  3449. [main reloadDatasource];
  3450. } else {
  3451. [self tableViewReloadData];
  3452. [app.activeTransfers reloadDatasource];
  3453. }
  3454. return;
  3455. }
  3456. [app.activeTransfers reloadDatasource];
  3457. // Settaggio variabili per le ottimizzazioni
  3458. _directoryGroupBy = [CCUtility getGroupBySettings];
  3459. _directoryOrder = [CCUtility getOrderSettings];
  3460. // Controllo data lettura Data Source
  3461. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3462. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3463. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3464. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3465. _dateReadDataSource = [NSDate date];
  3466. // Data Source
  3467. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3468. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3469. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3470. } else {
  3471. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3472. }
  3473. [self tableViewReloadData];
  3474. }
  3475. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3476. {
  3477. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3478. if (selectedRows.count > 0) {
  3479. for (NSIndexPath *selectionIndex in selectedRows) {
  3480. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3481. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3482. [metadatas addObject:metadata];
  3483. }
  3484. }
  3485. return metadatas;
  3486. }
  3487. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3488. {
  3489. NSInteger section = indexPath.section + 1;
  3490. NSInteger row = indexPath.row + 1;
  3491. NSInteger totSections =[_sectionDataSource.sections count] ;
  3492. if ((totSections < section) || (section > totSections)) {
  3493. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3494. return nil;
  3495. }
  3496. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3497. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3498. if (fileIDs) {
  3499. NSInteger totRows =[fileIDs count] ;
  3500. if ((totRows < row) || (row > totRows)) {
  3501. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3502. return nil;
  3503. }
  3504. } else {
  3505. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3506. return nil;
  3507. }
  3508. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3509. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3510. return metadata;
  3511. }
  3512. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3513. {
  3514. NSInteger totSections =[_sectionDataSource.sections count] ;
  3515. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3516. #if DEBUG
  3517. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3518. [alertView show];
  3519. #endif
  3520. return nil;
  3521. }
  3522. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3523. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3524. }
  3525. #pragma --------------------------------------------------------------------------------------------
  3526. #pragma mark - ==== Table ====
  3527. #pragma --------------------------------------------------------------------------------------------
  3528. - (void)tableViewSelect:(BOOL)edit
  3529. {
  3530. // chiudiamo eventuali swipe aperti
  3531. if (edit)
  3532. [self.tableView setEditing:NO animated:NO];
  3533. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3534. [self.tableView setEditing:edit animated:YES];
  3535. _isSelectedMode = edit;
  3536. if (edit)
  3537. [self setUINavigationBarSelected];
  3538. else
  3539. [self setUINavigationBarDefault];
  3540. [_selectedFileIDsMetadatas removeAllObjects];
  3541. [self setTitle];
  3542. }
  3543. - (void)tableViewReloadData
  3544. {
  3545. // store selected cells before relod
  3546. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3547. //store swipeOffset before relod
  3548. [_statusSwipeCell removeAllObjects];
  3549. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3550. NSIndexPath *path = [self.tableView indexPathForCell:cell];
  3551. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:[@(path.row) stringValue]];
  3552. }
  3553. // reload table view
  3554. [self.tableView reloadData];
  3555. // selected cells stored
  3556. for (NSIndexPath *path in indexPaths)
  3557. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3558. [self setTableViewFooter];
  3559. if (self.tableView.editing)
  3560. [self setTitle];
  3561. }
  3562. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3563. {
  3564. return 60;
  3565. }
  3566. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3567. {
  3568. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3569. }
  3570. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3571. {
  3572. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3573. }
  3574. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3575. {
  3576. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3577. NSString *sectionTitle = [sections objectAtIndex:section];
  3578. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3579. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3580. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3581. return 20.f;
  3582. }
  3583. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3584. {
  3585. float shift;
  3586. UIVisualEffectView *visualEffectView;
  3587. // Titolo
  3588. NSString *titleSection;
  3589. // Controllo
  3590. if ([_sectionDataSource.sections count] == 0)
  3591. return nil;
  3592. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3593. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3594. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3595. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3596. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3597. else titleSection = NSLocalizedString(titleSection,nil);
  3598. // Formato titolo
  3599. NSString *currentDevice = [CCUtility currentDevice];
  3600. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3601. visualEffectView = [[UIVisualEffectView alloc] init];
  3602. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3603. } else {
  3604. UIVisualEffect *blurEffect;
  3605. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3606. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3607. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3608. }
  3609. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3610. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3611. else shift = - 20;
  3612. } else shift = - 10;
  3613. // Title
  3614. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3615. titleLabel.backgroundColor = [UIColor clearColor];
  3616. titleLabel.textColor = [UIColor blackColor];
  3617. titleLabel.font = [UIFont systemFontOfSize:12];
  3618. titleLabel.textAlignment = NSTextAlignmentLeft;
  3619. titleLabel.text = titleSection;
  3620. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3621. [visualEffectView addSubview:titleLabel];
  3622. // Elements
  3623. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3624. elementLabel.backgroundColor = [UIColor clearColor];
  3625. elementLabel.textColor = [UIColor blackColor];;
  3626. elementLabel.font = [UIFont systemFontOfSize:12];
  3627. elementLabel.textAlignment = NSTextAlignmentRight;
  3628. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3629. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3630. NSUInteger rowsCount = [metadatas count];
  3631. if (rowsCount == 0) return nil;
  3632. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3633. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3634. [visualEffectView addSubview:elementLabel];
  3635. return visualEffectView;
  3636. }
  3637. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3638. {
  3639. return [_sectionDataSource.sections indexOfObject:title];
  3640. }
  3641. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3642. {
  3643. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3644. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3645. else
  3646. return nil;
  3647. }
  3648. /*
  3649. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3650. {
  3651. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3652. }
  3653. }
  3654. */
  3655. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3656. {
  3657. NSString *typeCell;
  3658. NSString *dataFile;
  3659. NSString *lunghezzaFile;
  3660. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3661. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3662. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3663. }
  3664. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3665. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3666. else typeCell = @"CellMainTransfer";
  3667. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3668. // variable base
  3669. cell.delegate = self;
  3670. cell.indexPath = indexPath;
  3671. // separator
  3672. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3673. // change color selection
  3674. UIView *selectionColor = [[UIView alloc] init];
  3675. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3676. cell.selectedBackgroundView = selectionColor;
  3677. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3678. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3679. // ----------------------------------------------------------------------------------------------------------
  3680. // DEFAULT
  3681. // ----------------------------------------------------------------------------------------------------------
  3682. cell.file.image = nil;
  3683. cell.status.image = nil;
  3684. cell.favorite.image = nil;
  3685. cell.shared.image = nil;
  3686. cell.local.image = nil;
  3687. cell.labelTitle.enabled = YES;
  3688. cell.labelTitle.text = @"";
  3689. cell.labelInfoFile.enabled = YES;
  3690. cell.labelInfoFile.text = @"";
  3691. cell.progressView.progress = 0.0;
  3692. cell.progressView.hidden = YES;
  3693. cell.cancelTaskButton.hidden = YES;
  3694. cell.reloadTaskButton.hidden = YES;
  3695. cell.stopTaskButton.hidden = YES;
  3696. // Encrypted color
  3697. if (metadata.cryptated) {
  3698. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3699. } else {
  3700. cell.labelTitle.textColor = [UIColor blackColor];
  3701. }
  3702. // ----------------------------------------------------------------------------------------------------------
  3703. // File Name & Folder
  3704. // ----------------------------------------------------------------------------------------------------------
  3705. // nome del file
  3706. cell.labelTitle.text = metadata.fileNamePrint;
  3707. // è una directory
  3708. if (metadata.directory) {
  3709. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3710. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3711. lunghezzaFile = @" ";
  3712. // ----------------------------------------------------------------------------------------------------------
  3713. // Favorite Folder
  3714. // ----------------------------------------------------------------------------------------------------------
  3715. if (metadata.favorite) {
  3716. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3717. }
  3718. } else {
  3719. // File
  3720. dataFile = [CCUtility dateDiff:metadata.date];
  3721. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3722. // Plist ancora da scaricare
  3723. if (metadata.cryptated && [metadata.title length] == 0) {
  3724. dataFile = @" ";
  3725. lunghezzaFile = @" ";
  3726. }
  3727. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3728. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3729. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3730. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3731. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3732. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3733. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3734. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3735. cell.local.image = [UIImage imageNamed:@"local"];
  3736. else
  3737. cell.local.image = nil;
  3738. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3739. //cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3740. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3741. }
  3742. // Plist ancora da scaricare
  3743. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3744. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3745. cell.accessoryType = UITableViewCellAccessoryNone;
  3746. }
  3747. // ----------------------------------------------------------------------------------------------------------
  3748. // File Image View
  3749. // ----------------------------------------------------------------------------------------------------------
  3750. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3751. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3752. cell.file.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3753. if (cell.file.image == nil) {
  3754. NSString *fileID = metadata.fileID;
  3755. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3756. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3757. [app.icoImagesCache setObject:image forKey:fileID];
  3758. dispatch_async(dispatch_get_main_queue(), ^{
  3759. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3760. if (cell)
  3761. cell.file.image = image;
  3762. });
  3763. });
  3764. }
  3765. } else {
  3766. if (metadata.directory)
  3767. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3768. else
  3769. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3770. if (metadata.thumbnailExists)
  3771. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3772. }
  3773. // ----------------------------------------------------------------------------------------------------------
  3774. // Image Status cyptated & Lock Passcode
  3775. // ----------------------------------------------------------------------------------------------------------
  3776. // File Cyptated
  3777. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3778. cell.status.image = [UIImage imageNamed:@"lock"];
  3779. }
  3780. // Directory con passcode lock attivato
  3781. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3782. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3783. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3784. cell.status.image = [UIImage imageNamed:@"passcode"];
  3785. // ----------------------------------------------------------------------------------------------------------
  3786. // Favorite
  3787. // ----------------------------------------------------------------------------------------------------------
  3788. if (metadata.favorite) {
  3789. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3790. }
  3791. // ----------------------------------------------------------------------------------------------------------
  3792. // Share
  3793. // ----------------------------------------------------------------------------------------------------------
  3794. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3795. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3796. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3797. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3798. // Aggiungiamo il Tap per le shared
  3799. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3800. if (isShare) {
  3801. if (metadata.directory) {
  3802. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3803. cell.shared.userInteractionEnabled = NO;
  3804. } else {
  3805. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3806. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3807. [tap setNumberOfTapsRequired:1];
  3808. cell.shared.userInteractionEnabled = YES;
  3809. [cell.shared addGestureRecognizer:tap];
  3810. }
  3811. }
  3812. if (isMounted) {
  3813. if (metadata.directory) {
  3814. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3815. cell.shared.userInteractionEnabled = NO;
  3816. } else {
  3817. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3818. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3819. [tap setNumberOfTapsRequired:1];
  3820. cell.shared.userInteractionEnabled = YES;
  3821. [cell.shared addGestureRecognizer:tap];
  3822. }
  3823. }
  3824. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3825. if (metadata.directory) {
  3826. if ([shareLink length] > 0)
  3827. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3828. if ([shareUserAndGroup length] > 0)
  3829. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3830. cell.shared.userInteractionEnabled = NO;
  3831. } else {
  3832. if ([shareLink length] > 0)
  3833. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3834. if ([shareUserAndGroup length] > 0)
  3835. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3836. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3837. [tap setNumberOfTapsRequired:1];
  3838. cell.shared.userInteractionEnabled = YES;
  3839. [cell.shared addGestureRecognizer:tap];
  3840. }
  3841. }
  3842. } else {
  3843. cell.shared.userInteractionEnabled = NO;
  3844. }
  3845. // ----------------------------------------------------------------------------------------------------------
  3846. // downloadFile
  3847. // ----------------------------------------------------------------------------------------------------------
  3848. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3849. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3850. else cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3851. // sessionTaskIdentifier : RELOAD + STOP
  3852. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3853. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3854. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3855. cell.cancelTaskButton.hidden = NO;
  3856. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3857. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3858. cell.reloadTaskButton.hidden = NO;
  3859. }
  3860. // sessionTaskIdentifierPlist : RELOAD
  3861. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3862. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3863. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3864. cell.reloadTaskButton.hidden = NO;
  3865. }
  3866. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3867. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3868. if (progress > 0) {
  3869. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3870. else cell.progressView.progressTintColor = [UIColor blackColor];
  3871. cell.progressView.progress = progress;
  3872. cell.progressView.hidden = NO;
  3873. }
  3874. // ----------------------------------------------------------------------------------------------------------
  3875. // downloadFile Error
  3876. // ----------------------------------------------------------------------------------------------------------
  3877. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3878. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3879. if ([metadata.sessionError length] == 0)
  3880. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3881. else
  3882. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3883. }
  3884. }
  3885. // ----------------------------------------------------------------------------------------------------------
  3886. // uploadFile
  3887. // ----------------------------------------------------------------------------------------------------------
  3888. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3889. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3890. else cell.status.image = [UIImage imageNamed:@"statusupload"];
  3891. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3892. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3893. cell.cancelTaskButton.hidden = NO;
  3894. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3895. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3896. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3897. if (metadata.cryptated) cell.status.image = [UIImage imageNamed:@"statusstopcrypto"];
  3898. else cell.status.image = [UIImage imageNamed:@"statusstop"];
  3899. cell.reloadTaskButton.hidden = NO;
  3900. cell.stopTaskButton.hidden = YES;
  3901. } else {
  3902. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3903. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3904. cell.stopTaskButton.hidden = NO;
  3905. cell.reloadTaskButton.hidden = YES;
  3906. }
  3907. // se non c'è una preview in bianconero metti l'immagine di default
  3908. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3909. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3910. cell.labelTitle.enabled = NO;
  3911. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3912. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3913. if (progress > 0) {
  3914. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3915. else cell.progressView.progressTintColor = [UIColor blackColor];
  3916. cell.progressView.progress = progress;
  3917. cell.progressView.hidden = NO;
  3918. }
  3919. // ----------------------------------------------------------------------------------------------------------
  3920. // uploadFileError
  3921. // ----------------------------------------------------------------------------------------------------------
  3922. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3923. cell.labelTitle.enabled = NO;
  3924. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3925. if ([metadata.sessionError length] == 0)
  3926. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3927. else
  3928. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3929. }
  3930. }
  3931. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3932. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3933. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3934. // MGSwipe
  3935. //configure left buttons
  3936. NSString *titleLeftButtonFavorite = [NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)];
  3937. if (metadata.favorite)
  3938. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:titleLeftButtonFavorite icon:[UIImage imageNamed:@"favorite"] backgroundColor:[UIColor redColor]]];
  3939. else
  3940. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:titleLeftButtonFavorite icon:[UIImage imageNamed:@"favorite"] backgroundColor:[UIColor greenColor]]];
  3941. cell.leftExpansion.buttonIndex = 0;
  3942. cell.leftExpansion.fillOnTrigger = NO;
  3943. //configure right buttons
  3944. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:NSLocalizedString(@"_delete_", nil) backgroundColor:[UIColor redColor]],
  3945. [MGSwipeButton buttonWithTitle:NSLocalizedString(@"_more_", nil) backgroundColor:[UIColor lightGrayColor]]];
  3946. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3947. //restore swipeOffset after relod
  3948. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:[@(indexPath.row) stringValue]] doubleValue];
  3949. if (swipeOffset < 0) {
  3950. //[cell setSwipeOffset:swipeOffset animated:NO completion:nil];
  3951. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3952. } else if (swipeOffset > 0) {
  3953. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3954. }
  3955. return cell;
  3956. }
  3957. - (void)setTableViewFooter
  3958. {
  3959. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3960. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3961. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3962. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3963. UIFont *appFont = [UIFont systemFontOfSize:12];
  3964. footerLabel.font = appFont;
  3965. footerLabel.textColor = [UIColor grayColor];
  3966. footerLabel.backgroundColor = [UIColor clearColor];
  3967. footerLabel.textAlignment = NSTextAlignmentCenter;
  3968. NSString *folders;
  3969. NSString *files;
  3970. NSString *footerText;
  3971. if (_sectionDataSource.directories > 1) {
  3972. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3973. } else if (_sectionDataSource.directories == 1){
  3974. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3975. } else {
  3976. folders = @"";
  3977. }
  3978. if (_sectionDataSource.files > 1) {
  3979. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3980. } else if (_sectionDataSource.files == 1){
  3981. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3982. } else {
  3983. files = @"";
  3984. }
  3985. if ([folders isEqualToString:@""]) {
  3986. footerText = files;
  3987. } else if ([files isEqualToString:@""]) {
  3988. footerText = folders;
  3989. } else {
  3990. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3991. }
  3992. footerLabel.text = footerText;
  3993. [footerView addSubview:footerLabel];
  3994. [self.tableView setTableFooterView:footerView];
  3995. }
  3996. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3997. {
  3998. NSString *textMessage;
  3999. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  4000. // settiamo il record file.
  4001. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  4002. // se non può essere selezionata deseleziona
  4003. if ([cell isEditing] == NO)
  4004. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  4005. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  4006. if (self.tableView.editing) {
  4007. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  4008. [self setTitle];
  4009. return;
  4010. }
  4011. // test crash
  4012. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  4013. if (indexPath.row >= [metadatas count]) return;
  4014. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4015. // se è in corso una sessione
  4016. if ([_metadata.session length] > 0) return;
  4017. if (_metadata.errorPasscode) {
  4018. // se UUID è nil lo sta ancora caricando quindi esci
  4019. if (!_metadata.uuid) return;
  4020. // esiste un hint ??
  4021. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  4022. // qui !! la richiesta della nuova passcode
  4023. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  4024. // stesso UUID ... la password è stata modificata !!!!!!
  4025. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  4026. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  4027. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4028. [alertView show];
  4029. } else {
  4030. // UUID diverso.
  4031. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  4032. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  4033. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4034. [alertView show];
  4035. }
  4036. // chiediamo la passcode e ricarichiamo tutto.
  4037. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4038. viewController.delegate = self;
  4039. viewController.fromType = CCBKPasscodeFromPasscode;
  4040. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4041. viewController.passcodeInputView.maximumLength = 64;
  4042. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4043. viewController.inputViewTitlePassword = NO;
  4044. viewController.title = [NCBrandOptions sharedInstance].brand;
  4045. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4046. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4047. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4048. [self presentViewController:navigationController animated:YES completion:nil];
  4049. }
  4050. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  4051. if (_metadata.cryptated && [_metadata.title length] == 0) {
  4052. NSString* selector;
  4053. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  4054. else selector = selectorLoadPlist;
  4055. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4056. return;
  4057. }
  4058. // se il plist è caricato ed è un modello aprilo
  4059. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4060. // file
  4061. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4062. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4063. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4064. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4065. } else {
  4066. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4067. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4068. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4069. }
  4070. }
  4071. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4072. }
  4073. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4074. {
  4075. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  4076. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  4077. [self setTitle];
  4078. }
  4079. #pragma --------------------------------------------------------------------------------------------
  4080. #pragma mark ===== Navigation ====
  4081. #pragma --------------------------------------------------------------------------------------------
  4082. - (BOOL)shouldPerformSegue
  4083. {
  4084. // if background return
  4085. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4086. if (self.view.window == NO)
  4087. return NO;
  4088. // Collapsed ma siamo già in detail esci
  4089. if (self.splitViewController.isCollapsed)
  4090. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4091. // Video in esecuzione esci
  4092. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4093. return YES;
  4094. }
  4095. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4096. {
  4097. id viewController = segue.destinationViewController;
  4098. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4099. tableMetadata *metadata;
  4100. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4101. UINavigationController *nav = viewController;
  4102. _detailViewController = (CCDetail *)nav.topViewController;
  4103. } else {
  4104. _detailViewController = segue.destinationViewController;
  4105. }
  4106. if ([sender isKindOfClass:[tableMetadata class]]) {
  4107. metadata = sender;
  4108. [allRecordsDataSourceImagesVideos addObject:sender];
  4109. } else {
  4110. metadata = _metadata;
  4111. for (NSString *fileID in _sectionDataSource.allEtag) {
  4112. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4113. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4114. [allRecordsDataSourceImagesVideos addObject:metadata];
  4115. }
  4116. }
  4117. _detailViewController.metadataDetail = metadata;
  4118. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4119. _detailViewController.dateFilterQuery = nil;
  4120. [_detailViewController setTitle:metadata.fileNamePrint];
  4121. }
  4122. // can i go to next viewcontroller
  4123. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4124. {
  4125. NSString *nomeDir;
  4126. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4127. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4128. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4129. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4130. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4131. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4132. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4133. viewController.delegate = self;
  4134. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4135. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4136. viewController.inputViewTitlePassword = YES;
  4137. if ([CCUtility getSimplyBlockCode]) {
  4138. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4139. viewController.passcodeInputView.maximumLength = 6;
  4140. } else {
  4141. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4142. viewController.passcodeInputView.maximumLength = 64;
  4143. }
  4144. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4145. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4146. viewController.touchIDManager = touchIDManager;
  4147. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4148. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4149. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4150. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4151. [self presentViewController:navController animated:YES completion:nil];
  4152. return;
  4153. }
  4154. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4155. else nomeDir = _metadata.fileName;
  4156. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4157. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4158. if (viewController.isViewLoaded == false || viewController == nil) {
  4159. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4160. viewController.isFolderEncrypted = _metadata.cryptated;
  4161. viewController.serverUrl = serverUrlPush;
  4162. viewController.titleMain = _metadata.fileNamePrint;
  4163. viewController.textBackButton = _titleMain;
  4164. // save self
  4165. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4166. }
  4167. // OFF SearchBar
  4168. [viewController cancelSearchBar];
  4169. [self.navigationController pushViewController:viewController animated:YES];
  4170. }
  4171. }
  4172. @end