CCMain.m 254 KB

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